using NPOI.SS.UserModel; using NPOI.SS.UserModel.Charts; using NPOI.SS.Util; using NPOI.XSSF.UserModel; using OTSCommon; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace OTSInclusionsTraceability { public partial class InclusionsTraceability : Form { #region 变量 /// /// 外来夹杂物种类 /// enum SourceType { RefiningSlag=0, Refractory=1, RefiningSlagAndRefractory=2 } string sEquivalentCircularDiameter = "30"; bool bContains = false; string sDisplaySource = "精炼渣"; string sElementsColName = ""; string sDefaultComputedColName = ""; DataOperation dataOperation; public string RetDBAddress = ""; DataTable particles; DataTable particlesDisplay; Dictionary keyValues = new Dictionary() { }; //国际化 Language lan; Hashtable table; #endregion public InclusionsTraceability() { //设置窗体的双缓冲,以保证大数据时拖动不卡 this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint, true); this.UpdateStyles(); InitializeComponent(); } private void InclusionsTraceability_Load(object sender, EventArgs e) { lan = new Language(this); table = lan.GetNameTable(this.Name); comboBox_SourceType.Items.Add(table["str1"]); comboBox_SourceType.Items.Add(table["str2"]); //comboBox_SourceType.Items.Add("精炼渣+耐材"); comboBox_SourceType.SelectedIndex = 0; Init(); tB_EquivalentCircularDiameter.Text = sEquivalentCircularDiameter; cB_contain.Checked = bContains; switch(sDisplaySource) { case "精炼渣": comboBox_SourceType.SelectedIndex = 0;break; case "耐材": comboBox_SourceType.SelectedIndex = 1; break; case "精炼渣+耐材": comboBox_SourceType.SelectedIndex = 2; break; case "Refining slag": comboBox_SourceType.SelectedIndex = 0; break; case "Refractory material": comboBox_SourceType.SelectedIndex = 1; break; case "Refining slag+Refractory material": comboBox_SourceType.SelectedIndex = 2; break; } #region 界面缩放控件位置记录 int count = this.Controls.Count * 2 + 2; float[] nature = new float[count]; int i = 0; nature[i++] = Size.Width; nature[i++] = Size.Height; foreach (Control ctrl in this.Controls) { nature[i++] = ctrl.Location.X / (float)Size.Width; nature[i++] = ctrl.Location.Y / (float)Size.Height; ctrl.Tag = ctrl.Size; } Tag = nature; #endregion tB_EquivalentCircularDiameter.Select(tB_EquivalentCircularDiameter.Text.Length, 0); } string AuquireEquCircleDiameter() { string condition = ""; double EquCircleDiameter = 0; if (double.TryParse(tB_EquivalentCircularDiameter.Text,out EquCircleDiameter)) { double Darea = Math.PI * (EquCircleDiameter * EquCircleDiameter / 4); if(cB_contain.Checked) { condition = "Area>=" + Darea.ToString(); } else { condition = "Area>" + Darea.ToString(); } } return condition; } /// /// DataRow转换为DataTable /// /// /// 筛选的条件 /// public DataTable SreeenDataTable(DataTable dt, string strWhere) { if (dt.Rows.Count <= 0) return dt; //当数据为空时返回 DataTable dtNew = dt.Clone(); //复制数据源的表结构 DataRow[] dr = dt.Select(strWhere); //strWhere条件筛选出需要的数据! for (int i = 0; i < dr.Length; i++) { dtNew.Rows.Add(dr[i].ItemArray); // 将DataRow添加到DataTable中 } return dtNew; } private void bn_Find_Click(object sender, EventArgs e) { string condition = AuquireEquCircleDiameter(); if (condition == "") { MessageBox.Show("Please enter valid data!"); return; } if(comboBox_SourceType.SelectedIndex==(int)SourceType.RefiningSlag) { condition += " and TypeName Like \'%CaO%\' "; } else if(comboBox_SourceType.SelectedIndex == (int)SourceType.Refractory) { condition += " and (TypeName Like \'%MgO%\' or TypeName Like \'%Al2O3%\')"; } else { condition += " and (TypeName Like \'%MgO%\' or TypeName Like \'%Al2O3%\' or TypeName Like \'%CaO%\')"; } particlesDisplay = SreeenDataTable(particles, condition); DataTable elementchemistry = dataOperation.GetElementChemistry(); for (int i = 0; i < particlesDisplay.Rows.Count; i++) { string str = "XRayId = " + particlesDisplay.Rows[i]["particleId"].ToString() + " and fieldid = " + particlesDisplay.Rows[i]["fieldid"].ToString(); DataRow[] drs = elementchemistry.Select(str); string ConcatenatedString = ""; for (int j = 0; j < drs.Length; j++) { ConcatenatedString += drs[j]["name"] + "-" + drs[j]["Percentage"] + ';'; } particlesDisplay.Rows[i]["Element"] = ConcatenatedString; } BindDataGridView(); SetDataGridViewStyle(); dataOperation.WriteXmlDefaultData(tB_EquivalentCircularDiameter.Text, cB_contain.Checked,(comboBox_SourceType.SelectedItem).ToString()); } void BindDataGridView() { dgV_Traceablilty.Visible = false; this.Cursor = Cursors.WaitCursor; if (particlesDisplay== null) { return; } dgV_Traceablilty.Rows.Clear(); //获取需要显示的元素名 List ElementTypeSort = new List(sElementsColName.Split(',').ToList());//去重 //double jd = 95f / (double)particles.Rows.Count;//计算进度刻度 string filePath = ""; if (RetDBAddress.Contains("db")) { filePath = Directory.GetParent(RetDBAddress).FullName+"\\"; } else { filePath = RetDBAddress + "\\FIELD_FILES\\"; } KeyValuePair FieldImage = new KeyValuePair(); for (int i = 0; i < particlesDisplay.Rows.Count; i++) { //更新进度,每100条记录加载完,更新一次进度 //if (i % 10 == 0) // m_frm_userprogress.SetProgressValueAndText((int)(jd * i), "loading.."); Dictionary.Enumerator enl = keyValues.GetEnumerator(); int add_rowindex = dgV_Traceablilty.Rows.Add(); dgV_Traceablilty.Rows[add_rowindex].Cells[0].Value = (add_rowindex + 1).ToString(); for (int k = 0; k < keyValues.Count; k++) { if (enl.MoveNext()) { if (enl.Current.Key == "rowid") { //dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = i + 1; } if (enl.Current.Key == "ParticleImage") { if (FieldImage.Key != particlesDisplay.Rows[i]["fieldid"].ToString() || FieldImage.Value == null) { string imagePath = filePath + "Field" + particlesDisplay.Rows[i]["fieldid"].ToString() + ".bmp"; FieldImage = new KeyValuePair(particlesDisplay.Rows[i]["fieldid"].ToString(), dataOperation.ReadImageFile(imagePath)); } Rectangle rectangle = new Rectangle() { X = Convert.ToInt32(particlesDisplay.Rows[i]["RectLeft"]), Y = Convert.ToInt32(particlesDisplay.Rows[i]["RectTop"]), Width = Convert.ToInt32(particlesDisplay.Rows[i]["RectWidth"]), Height = Convert.ToInt32(particlesDisplay.Rows[i]["RectHeight"]) }; Bitmap bmap = dataOperation.GetBitmapByParticle(FieldImage.Value, rectangle); bmap.Tag = new List() { particlesDisplay.Rows[i]["FieldId"].ToString(), particlesDisplay.Rows[i]["ParticleId"].ToString(), particlesDisplay.Rows[i]["TypeId"].ToString(), particlesDisplay.Rows[i]["XrayId"].ToString() }; dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = bmap; dgV_Traceablilty.Rows[add_rowindex].Height = bmap.Height + 20; } //if (enl.Current.Key == "SourceType") //{ // if (particlesDisplay.Rows[i]["TypeName"].ToString().Contains("CaO")) // { // dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = SourceType.RefiningSlag.ToString(); // } // else // { // dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = SourceType.Refractory.ToString(); // } //} if (enl.Current.Key == "DiameterRatio") { double d = Convert.ToDouble(particlesDisplay.Rows[i]["DMAX"]) / Convert.ToDouble(particlesDisplay.Rows[i]["DMIN"]); dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = Math.Round(d, 2); } if (enl.Current.Key == "ASPECT_ELONG") { double d = Convert.ToDouble(particlesDisplay.Rows[i]["DELONG"]) / Convert.ToDouble(particlesDisplay.Rows[i]["DMEAN"]); dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = Math.Round(d, 2); } if (particlesDisplay.Columns.Contains(enl.Current.Key)) { double num = 0; if (double.TryParse(particlesDisplay.Rows[i][enl.Current.Key].ToString(), out num)) { dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = Math.Round(num, 2); } else if (enl.Current.Key == "Element") { List elementtemp = new List(ElementTypeSort); string[] strcbo = particlesDisplay.Rows[i][enl.Current.Key].ToString().Split(';'); for (int j = 0; j < strcbo.Length; j++) { string[] str = strcbo[j].Split('-'); if (ElementTypeSort.Contains(str[0])) { dgV_Traceablilty.Rows[add_rowindex].Cells[str[0].ToString()].Value = Math.Round(double.Parse(str[1]), 2).ToString(); } elementtemp.Remove(str[0].ToString()); } foreach (var ele in elementtemp) { dgV_Traceablilty.Rows[add_rowindex].Cells[ele].Value = "0"; } } else { dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = particlesDisplay.Rows[i][enl.Current.Key]; } } //if (enl.Current.Key == "TypeName") //{ // if (particlesDisplay.Rows[i]["TypeId"].ToString() == "9") // { // dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = "Not Identified"; // } //} if (enl.Current.Key == "Equivalent") { double dSize = Convert.ToDouble(particlesDisplay.Rows[i]["Area"]); double Diameter = Math.Sqrt(dSize / Math.PI) * 2; dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = Math.Round(Diameter, 2); } } } } #region 加载进度条进度部份结束 //加载完成设置鼠标为默认 this.Cursor = Cursors.Default; //string str8 = table["str8"].ToString(); //m_frm_userprogress.SetProgressValueAndText(100, str8); ////加载完成,关闭进度条 //m_frm_userprogress.Close(); #endregion dgV_Traceablilty.Visible = true; } void Init() { #region 数据库及表格 dataOperation = new DataOperation(RetDBAddress); particles = dataOperation.GetParticlesByEquCircleDiameter("", ""); #endregion #region XML 文档 dataOperation.ReadXmlDataDefault("ElementsColName", ref sElementsColName, "\\Config\\SysData\\OTSReportMgrParam.rpf"); dataOperation.ReadXmlDataDefault("DefaultComputedColName", ref sDefaultComputedColName, "\\Config\\SysData\\OTSReportMgrParam.rpf"); string sContains = ""; if (dataOperation.ReadXmlDataDefault("Contains", ref sContains)) { if (sContains == "True") { bContains = true; } dataOperation.ReadXmlDataDefault("EquivalentCircularDiameter", ref sEquivalentCircularDiameter); dataOperation.ReadXmlDataDefault("DisplaySource", ref sDisplaySource); } #endregion #region 表格 dgV_Traceablilty.Rows.Clear(); dgV_Traceablilty.Columns.Clear(); //获取需要显示的计算列 string[] strs = sDefaultComputedColName.Split(','); //列名 keyValues.Add("rowid", table["str4"].ToString()); keyValues.Add("TypeName", table["str6"].ToString()); keyValues.Add("ParticleImage", table["str5"].ToString()); //keyValues.Add("SourceType", table["str34"].ToString()); keyValues.Add("FieldId", "FieldId"); keyValues.Add("ParticleId", "ParticleId"); for (int i = 0; i < strs.Count(); i++) { if (strs[i] == "FiledCoordinate") { keyValues.Add("SEMPosX", "SEMPosX"); keyValues.Add("SEMPosY", "SEMPosY"); } if (strs[i] == "Area") { keyValues.Add("Area", table["str21"].ToString()); } if (strs[i] == "EquivalentCircleDiameter") { keyValues.Add("Equivalent", table["str22"].ToString()); } if (strs[i] == "MaxDiameter") { keyValues.Add("DMAX", table["str23"].ToString()); } if (strs[i] == "MinDiameter") { keyValues.Add("DMIN", table["str24"].ToString()); } if (strs[i] == "DiameterRatio") { keyValues.Add("DiameterRatio", table["str25"].ToString()); } if (strs[i] == "FerretDiameter") { keyValues.Add("DFERET", table["str26"].ToString()); } if (strs[i] == "PERP") { keyValues.Add("DPERP", table["str27"].ToString()); } if (strs[i] == "PERI") { keyValues.Add("PERIMETER", table["str28"].ToString()); } if (strs[i] == "INSCR") { keyValues.Add("DINSCR", table["str29"].ToString()); } if (strs[i] == "MEAN") { keyValues.Add("DMEAN", table["str30"].ToString()); } if (strs[i] == "ELONG") { keyValues.Add("DELONG", table["str31"].ToString()); } if (strs[i] == "ASPECT_ELONG") { keyValues.Add("ASPECT_ELONG", table["str32"].ToString()); } if (strs[i] == "Orientation") { keyValues.Add("ORIENTATION", table["str33"].ToString()); } } keyValues.Add("Element", "Element"); Dictionary.Enumerator en = keyValues.GetEnumerator(); for (int irow = 0; irow < keyValues.Count; irow++) { if (en.MoveNext()) { if (en.Current.Key == "ParticleImage") { DataGridViewImageColumn iconColumn = new DataGridViewImageColumn(); iconColumn.Name = en.Current.Key; iconColumn.HeaderText = en.Current.Value; dgV_Traceablilty.Columns.Add(iconColumn); } else if (en.Current.Key == "Element") { } else { int columndid = dgV_Traceablilty.Columns.Add(en.Current.Key, en.Current.Value); } } } //获取需要显示的元素名 List ElementTypeSort = new List(sElementsColName.Split(',').ToList());//去重 for (int i = 0; i < ElementTypeSort.Count; i++) { dgV_Traceablilty.Columns.Add(ElementTypeSort[i], ElementTypeSort[i]); } #endregion } /// /// 设置DataGridView样式 /// private void SetDataGridViewStyle() { //用户不能调整标题的高度 dgV_Traceablilty.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; //用户不能调整 行高 dgV_Traceablilty.AllowUserToResizeRows = false; //点击选择整行 dgV_Traceablilty.SelectionMode = DataGridViewSelectionMode.FullRowSelect; //居中显示 System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; dgV_Traceablilty.DefaultCellStyle = dataGridViewCellStyle1; dgV_Traceablilty.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //再次重覆禁用拖动表头高度,居然有效果了 dgV_Traceablilty.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; //设置grid可以复制 dgV_Traceablilty.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText; //设置每列的宽度 dgV_Traceablilty.Columns[0].Width = 40;//第一列序号的宽度设置一下吧,要不太丑 dgV_Traceablilty.Columns[1].Width = 150; //dgV_Traceablilty.Columns[dgV_Traceablilty.Columns.Count - 1].Width = 450; //dgV_Traceablilty.Columns[dgV_Traceablilty.Columns.Count - 1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft; //设置序号列不排序 dgV_Traceablilty.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable; //设置序号列不可以设置宽度 dgV_Traceablilty.Columns[0].Resizable = DataGridViewTriState.False; dgV_Traceablilty.RowsDefaultCellStyle.BackColor = Color.Azure; } private void InclusionsTraceability_Resize(object sender, EventArgs e) { } private void ExportExecl_Click(object sender, EventArgs e) { //将所有的数据导出到EXCEL中 SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Excel File(*.xlsx)|*.xlsx"; //设置默认文件类型显示顺序 sfd.FilterIndex = 1; sfd.FileName = "ParticlesInfo"; //保存对话框是否记忆上次打开的目录 sfd.RestoreDirectory = true; if (sfd.ShowDialog() == DialogResult.OK) { //IWorkbook workbook = new HSSFWorkbook(); //用于创建.xls office2003开始以前的 IWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(); //用于创建.xlsx office2007开始以后的 ISheet sheet; //创建Excel文件 FileStream fs = File.Create(sfd.FileName); fs.Close(); sheet = workbook.CreateSheet("Particles");//创建工作表 //创建表格边框样式风格 ICellStyle cellStyle = workbook.CreateCellStyle(); cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; cellStyle.VerticalAlignment = VerticalAlignment.Center; //设置上4边 cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; //设置字符大小和颜色 IFont font = workbook.CreateFont(); font.FontName = "黑体"; font.FontHeightInPoints = 10; cellStyle.SetFont(font); //设置颗粒名列宽 sheet.SetColumnWidth(1, 30 * 256);//夹杂物名列宽 sheet.SetColumnWidth(2, 7 * 256);//图像列宽 IRow row; ICell cell; //插入表头 row = sheet.CreateRow(1);//从第15行添加一行 row.Height = 30 * 20; for (int i_cell = 0; i_cell < dgV_Traceablilty.Columns.Count; i_cell++) { cell = row.CreateCell(i_cell); cell.CellStyle = cellStyle; cell.SetCellValue(dgV_Traceablilty.Columns[i_cell].Name); } //插入表内容 for (int i_row = 0; i_row < dgV_Traceablilty.Rows.Count; i_row++) { row = sheet.CreateRow(2 + i_row); row.Height = 45 * 20; for (int i_cell = 0; i_cell < dgV_Traceablilty.Columns.Count; i_cell++) { cell = row.CreateCell(i_cell); cell.CellStyle = cellStyle; if (dgV_Traceablilty[i_cell, i_row].Value == null) continue; if (i_cell == 2) { //颗粒图像列 Bitmap bp = (Bitmap)dgV_Traceablilty.Rows[i_row].Cells[2].Value; byte[] bytes = ImageConvertToBytes(bp); //第二步,将图片添加到workbook中,指定图片的格式,返回图片所在workbook->paicture数组中的索引的地址,从1开始 int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG); //第三步,在sheet中创建画布 IDrawing patriarch = sheet.CreateDrawingPatriarch(); //第四步,设置锚点,(在起始单元格的X坐标0-1023,Y的坐标0-255,在终止单元格的X坐标0-1023,Y的坐标0-255,起始单元格行数,列数,终止单元格行数,列数) IClientAnchor anchor = patriarch.CreateAnchor(1, 1, 2, 2, i_cell, i_row + 2, i_cell + 1, i_row + 3);//终止比开始位置大1,会自动缩放到一个单元格内的 //第五步,创建图片 IPicture pict = patriarch.CreatePicture(anchor, pictureIdx); //图像效果不好,自己另外导出吧,这里对该列宽进行了设置0 } else { //非图像列 double dbl = 0; if (double.TryParse(dgV_Traceablilty[i_cell, i_row].Value.ToString(), out dbl)) { cell.SetCellValue(dbl); } else { cell.SetCellValue(dgV_Traceablilty[i_cell, i_row].Value.ToString()); } } } } //完成后,对Excel进行保存 FileStream file = new FileStream(sfd.FileName, FileMode.Create); workbook.Write(file); file.Close(); MessageBox.Show("Export complete!"); //导出完成后,打开Excel文件 if (File.Exists(sfd.FileName)) { //打开刚才导出的文件 System.Diagnostics.Process.Start(sfd.FileName); } } } /// /// 将image转成bytes /// /// /// public byte[] ImageConvertToBytes(System.Drawing.Image in_img) { MemoryStream ms = new MemoryStream(); in_img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); return ms.ToArray(); } void CreateChart(IDrawing drawing, ISheet sheet, IClientAnchor anchor, int rowid) { var chart = drawing.CreateChart(anchor) as XSSFChart; //图表 var data = chart.ChartDataFactory.CreateLineChartData(); //折线图 IChartAxis bottomAxis = chart.ChartAxisFactory.CreateCategoryAxis(AxisPosition.Bottom); IValueAxis leftAxis = chart.ChartAxisFactory.CreateValueAxis(AxisPosition.Left); leftAxis.Crosses = AxisCrosses.AutoZero; leftAxis.IsVisible = true; bottomAxis.IsVisible = true; //数据源 IChartDataSource ys = DataSources.FromNumericCellRange(sheet, new CellRangeAddress(rowid, rowid, 1, 2001)); Double[] doubles = new Double[2000]; for (int i = 0; i < 2000; i++) { doubles[i] = i; } IChartDataSource xs = DataSources.FromArray(doubles); //数据系列 var s1 = data.AddSeries(xs, ys); // 开始绘制折线图 chart.Plot(data, bottomAxis, leftAxis); } private void 复制全部ToolStripMenuItem_Click(object sender, EventArgs e) { //复制整个表 CopyAll(); } /// /// 复制所有 /// public void CopyAll() { dgV_Traceablilty.SelectAll(); Clipboard.SetDataObject(dgV_Traceablilty.GetClipboardContent()); } private void CopySelectToolStripMenuItem1_Click(object sender, EventArgs e) { //复制选择区域 CopySelected(); } /// /// 复制选择区域 /// public void CopySelected() { //复制选择区域 object oo = dgV_Traceablilty.GetClipboardContent(); if (oo != null) Clipboard.SetDataObject(dgV_Traceablilty.GetClipboardContent()); } private void 复制图像ToolStripMenuItem_Click(object sender, EventArgs e) { //对gridview进行截图 CopyImage(); } /// /// 以图像的方式将GridView进行截图 /// public void CopyImage() { int height, width; width = dgV_Traceablilty.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) + 2; height = this.Height; Bitmap image = new Bitmap(width, height); dgV_Traceablilty.DrawToBitmap(image, new Rectangle(0, 0, width, height)); Clipboard.SetImage(image); } } }