OTSInclusionsTraceability.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. using NPOI.SS.UserModel;
  2. using NPOI.SS.UserModel.Charts;
  3. using NPOI.SS.Util;
  4. using NPOI.XSSF.UserModel;
  5. using OTSCommon;
  6. using System;
  7. using System.Collections;
  8. using System.Collections.Generic;
  9. using System.ComponentModel;
  10. using System.Data;
  11. using System.Drawing;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Text;
  15. using System.Threading.Tasks;
  16. using System.Windows.Forms;
  17. namespace OTSInclusionsTraceability
  18. {
  19. public partial class InclusionsTraceability : Form
  20. {
  21. #region 变量
  22. /// <summary>
  23. /// 外来夹杂物种类
  24. /// </summary>
  25. enum SourceType
  26. {
  27. RefiningSlag=0,
  28. Refractory=1,
  29. RefiningSlagAndRefractory=2
  30. }
  31. string sEquivalentCircularDiameter = "30";
  32. bool bContains = false;
  33. string sDisplaySource = "精炼渣";
  34. string sElementsColName = "";
  35. string sDefaultComputedColName = "";
  36. DataOperation dataOperation;
  37. public string RetDBAddress = "";
  38. DataTable particles;
  39. DataTable particlesDisplay;
  40. Dictionary<string, string> keyValues = new Dictionary<string, string>() { };
  41. //国际化
  42. Language lan;
  43. Hashtable table;
  44. #endregion
  45. public InclusionsTraceability()
  46. {
  47. //设置窗体的双缓冲,以保证大数据时拖动不卡
  48. this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint, true);
  49. this.UpdateStyles();
  50. InitializeComponent();
  51. }
  52. private void InclusionsTraceability_Load(object sender, EventArgs e)
  53. {
  54. comboBox_SourceType.Items.Add("精炼渣");
  55. comboBox_SourceType.Items.Add("耐材");
  56. //comboBox_SourceType.Items.Add("精炼渣+耐材");
  57. comboBox_SourceType.SelectedIndex = 0;
  58. Init();
  59. tB_EquivalentCircularDiameter.Text = sEquivalentCircularDiameter;
  60. cB_contain.Checked = bContains;
  61. switch(sDisplaySource)
  62. {
  63. case "精炼渣": comboBox_SourceType.SelectedIndex = 0;break;
  64. case "耐材": comboBox_SourceType.SelectedIndex = 1; break;
  65. case "精炼渣+耐材": comboBox_SourceType.SelectedIndex = 2; break;
  66. }
  67. #region 界面缩放控件位置记录
  68. int count = this.Controls.Count * 2 + 2;
  69. float[] nature = new float[count];
  70. int i = 0;
  71. nature[i++] = Size.Width;
  72. nature[i++] = Size.Height;
  73. foreach (Control ctrl in this.Controls)
  74. {
  75. nature[i++] = ctrl.Location.X / (float)Size.Width;
  76. nature[i++] = ctrl.Location.Y / (float)Size.Height;
  77. ctrl.Tag = ctrl.Size;
  78. }
  79. Tag = nature;
  80. #endregion
  81. tB_EquivalentCircularDiameter.Select(tB_EquivalentCircularDiameter.Text.Length, 0);
  82. }
  83. string AuquireEquCircleDiameter()
  84. {
  85. string condition = "";
  86. double EquCircleDiameter = 0;
  87. if (double.TryParse(tB_EquivalentCircularDiameter.Text,out EquCircleDiameter))
  88. {
  89. double Darea = Math.PI * (EquCircleDiameter * EquCircleDiameter / 4);
  90. if(cB_contain.Checked)
  91. {
  92. condition = "Area>=" + Darea.ToString();
  93. }
  94. else
  95. {
  96. condition = "Area>" + Darea.ToString();
  97. }
  98. }
  99. return condition;
  100. }
  101. /// <summary>
  102. /// DataRow转换为DataTable
  103. /// </summary>
  104. /// <param name="dt"></param>
  105. /// <param name="strWhere">筛选的条件</param>
  106. /// <returns></returns>
  107. public DataTable SreeenDataTable(DataTable dt, string strWhere)
  108. {
  109. if (dt.Rows.Count <= 0) return dt; //当数据为空时返回
  110. DataTable dtNew = dt.Clone(); //复制数据源的表结构
  111. DataRow[] dr = dt.Select(strWhere); //strWhere条件筛选出需要的数据!
  112. for (int i = 0; i < dr.Length; i++)
  113. {
  114. dtNew.Rows.Add(dr[i].ItemArray); // 将DataRow添加到DataTable中
  115. }
  116. return dtNew;
  117. }
  118. private void bn_Find_Click(object sender, EventArgs e)
  119. {
  120. string condition = AuquireEquCircleDiameter();
  121. if (condition == "")
  122. {
  123. MessageBox.Show("请输入有效的数据!");
  124. return;
  125. }
  126. if(comboBox_SourceType.SelectedIndex==(int)SourceType.RefiningSlag)
  127. {
  128. condition += " and TypeName Like \'%CaO%\' ";
  129. }
  130. else if(comboBox_SourceType.SelectedIndex == (int)SourceType.Refractory)
  131. {
  132. condition += " and (TypeName Like \'%MgO%\' or TypeName Like \'%Al2O3%\')";
  133. }
  134. else
  135. {
  136. condition += " and (TypeName Like \'%MgO%\' or TypeName Like \'%Al2O3%\' or TypeName Like \'%CaO%\')";
  137. }
  138. particlesDisplay = SreeenDataTable(particles, condition);
  139. DataTable elementchemistry = dataOperation.GetElementChemistry();
  140. for (int i = 0; i < particlesDisplay.Rows.Count; i++)
  141. {
  142. string str = "XRayId = " + particlesDisplay.Rows[i]["particleId"].ToString() + " and fieldid = " + particlesDisplay.Rows[i]["fieldid"].ToString();
  143. DataRow[] drs = elementchemistry.Select(str);
  144. string ConcatenatedString = "";
  145. for (int j = 0; j < drs.Length; j++)
  146. {
  147. ConcatenatedString += drs[j]["name"] + "-" + drs[j]["Percentage"] + ';';
  148. }
  149. particlesDisplay.Rows[i]["Element"] = ConcatenatedString;
  150. }
  151. BindDataGridView();
  152. SetDataGridViewStyle();
  153. dataOperation.WriteXmlDefaultData(tB_EquivalentCircularDiameter.Text, cB_contain.Checked,(comboBox_SourceType.SelectedItem).ToString());
  154. }
  155. void BindDataGridView()
  156. {
  157. dgV_Traceablilty.Visible = false;
  158. this.Cursor = Cursors.WaitCursor;
  159. if (particlesDisplay== null)
  160. {
  161. return;
  162. }
  163. dgV_Traceablilty.Rows.Clear();
  164. //获取需要显示的元素名
  165. List<string> ElementTypeSort = new List<string>(sElementsColName.Split(',').ToList());//去重
  166. //double jd = 95f / (double)particles.Rows.Count;//计算进度刻度
  167. string filePath = "";
  168. if (RetDBAddress.Contains("db"))
  169. {
  170. filePath = Directory.GetParent(RetDBAddress).FullName+"\\";
  171. }
  172. else
  173. {
  174. filePath = RetDBAddress + "\\FIELD_FILES\\";
  175. }
  176. KeyValuePair<string, Bitmap> FieldImage = new KeyValuePair<string, Bitmap>();
  177. for (int i = 0; i < particlesDisplay.Rows.Count; i++)
  178. {
  179. //更新进度,每100条记录加载完,更新一次进度
  180. //if (i % 10 == 0)
  181. // m_frm_userprogress.SetProgressValueAndText((int)(jd * i), "loading..");
  182. Dictionary<string, string>.Enumerator enl = keyValues.GetEnumerator();
  183. int add_rowindex = dgV_Traceablilty.Rows.Add();
  184. dgV_Traceablilty.Rows[add_rowindex].Cells[0].Value = (add_rowindex + 1).ToString();
  185. for (int k = 0; k < keyValues.Count; k++)
  186. {
  187. if (enl.MoveNext())
  188. {
  189. if (enl.Current.Key == "rowid")
  190. {
  191. //dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = i + 1;
  192. }
  193. if (enl.Current.Key == "ParticleImage")
  194. {
  195. if (FieldImage.Key != particlesDisplay.Rows[i]["fieldid"].ToString() || FieldImage.Value == null)
  196. {
  197. string imagePath = filePath + "Field" + particlesDisplay.Rows[i]["fieldid"].ToString() + ".bmp";
  198. FieldImage = new KeyValuePair<string, Bitmap>(particlesDisplay.Rows[i]["fieldid"].ToString(), dataOperation.ReadImageFile(imagePath));
  199. }
  200. 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"]) };
  201. Bitmap bmap = dataOperation.GetBitmapByParticle(FieldImage.Value, rectangle);
  202. bmap.Tag = new List<string>() { particlesDisplay.Rows[i]["FieldId"].ToString(), particlesDisplay.Rows[i]["ParticleId"].ToString(), particlesDisplay.Rows[i]["TypeId"].ToString(), particlesDisplay.Rows[i]["XrayId"].ToString() };
  203. dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = bmap;
  204. dgV_Traceablilty.Rows[add_rowindex].Height = bmap.Height + 20;
  205. }
  206. //if (enl.Current.Key == "SourceType")
  207. //{
  208. // if (particlesDisplay.Rows[i]["TypeName"].ToString().Contains("CaO"))
  209. // {
  210. // dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = SourceType.RefiningSlag.ToString();
  211. // }
  212. // else
  213. // {
  214. // dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = SourceType.Refractory.ToString();
  215. // }
  216. //}
  217. if (enl.Current.Key == "DiameterRatio")
  218. {
  219. double d = Convert.ToDouble(particlesDisplay.Rows[i]["DMAX"]) / Convert.ToDouble(particlesDisplay.Rows[i]["DMIN"]);
  220. dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = Math.Round(d, 2);
  221. }
  222. if (enl.Current.Key == "ASPECT_ELONG")
  223. {
  224. double d = Convert.ToDouble(particlesDisplay.Rows[i]["DELONG"]) / Convert.ToDouble(particlesDisplay.Rows[i]["DMEAN"]);
  225. dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = Math.Round(d, 2);
  226. }
  227. if (particlesDisplay.Columns.Contains(enl.Current.Key))
  228. {
  229. double num = 0;
  230. if (double.TryParse(particlesDisplay.Rows[i][enl.Current.Key].ToString(), out num))
  231. {
  232. dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = Math.Round(num, 2);
  233. }
  234. else if (enl.Current.Key == "Element")
  235. {
  236. List<string> elementtemp = new List<string>(ElementTypeSort);
  237. string[] strcbo = particlesDisplay.Rows[i][enl.Current.Key].ToString().Split(';');
  238. for (int j = 0; j < strcbo.Length; j++)
  239. {
  240. string[] str = strcbo[j].Split('-');
  241. if (ElementTypeSort.Contains(str[0]))
  242. { dgV_Traceablilty.Rows[add_rowindex].Cells[str[0].ToString()].Value = Math.Round(double.Parse(str[1]), 2).ToString(); }
  243. elementtemp.Remove(str[0].ToString());
  244. }
  245. foreach (var ele in elementtemp)
  246. {
  247. dgV_Traceablilty.Rows[add_rowindex].Cells[ele].Value = "0";
  248. }
  249. }
  250. else
  251. {
  252. dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = particlesDisplay.Rows[i][enl.Current.Key];
  253. }
  254. }
  255. //if (enl.Current.Key == "TypeName")
  256. //{
  257. // if (particlesDisplay.Rows[i]["TypeId"].ToString() == "9")
  258. // {
  259. // dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = "Not Identified";
  260. // }
  261. //}
  262. if (enl.Current.Key == "Equivalent")
  263. {
  264. double dSize = Convert.ToDouble(particlesDisplay.Rows[i]["Area"]);
  265. double Diameter = Math.Sqrt(dSize / Math.PI) * 2;
  266. dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = Math.Round(Diameter, 2);
  267. }
  268. }
  269. }
  270. }
  271. #region 加载进度条进度部份结束
  272. //加载完成设置鼠标为默认
  273. this.Cursor = Cursors.Default;
  274. //string str8 = table["str8"].ToString();
  275. //m_frm_userprogress.SetProgressValueAndText(100, str8);
  276. ////加载完成,关闭进度条
  277. //m_frm_userprogress.Close();
  278. #endregion
  279. dgV_Traceablilty.Visible = true;
  280. }
  281. void Init()
  282. {
  283. lan = new Language(this);
  284. table = lan.GetNameTable(this.Name);
  285. #region 数据库及表格
  286. dataOperation = new DataOperation(RetDBAddress);
  287. particles = dataOperation.GetParticlesByEquCircleDiameter("", "");
  288. #endregion
  289. #region XML 文档
  290. dataOperation.ReadXmlDataDefault("ElementsColName", ref sElementsColName, "\\Config\\SysData\\OTSReportMgrParam.rpf");
  291. dataOperation.ReadXmlDataDefault("DefaultComputedColName", ref sDefaultComputedColName, "\\Config\\SysData\\OTSReportMgrParam.rpf");
  292. string sContains = "";
  293. if (dataOperation.ReadXmlDataDefault("Contains", ref sContains))
  294. {
  295. if (sContains == "True")
  296. {
  297. bContains = true;
  298. }
  299. dataOperation.ReadXmlDataDefault("EquivalentCircularDiameter", ref sEquivalentCircularDiameter);
  300. dataOperation.ReadXmlDataDefault("DisplaySource", ref sDisplaySource);
  301. }
  302. #endregion
  303. #region 表格
  304. dgV_Traceablilty.Rows.Clear();
  305. dgV_Traceablilty.Columns.Clear();
  306. //获取需要显示的计算列
  307. string[] strs = sDefaultComputedColName.Split(',');
  308. //列名
  309. keyValues.Add("rowid", table["str4"].ToString());
  310. keyValues.Add("TypeName", table["str6"].ToString());
  311. keyValues.Add("ParticleImage", table["str5"].ToString());
  312. //keyValues.Add("SourceType", table["str34"].ToString());
  313. keyValues.Add("FieldId", "FieldId");
  314. keyValues.Add("ParticleId", "ParticleId");
  315. for (int i = 0; i < strs.Count(); i++)
  316. {
  317. if (strs[i] == "FiledCoordinate")
  318. {
  319. keyValues.Add("SEMPosX", "SEMPosX");
  320. keyValues.Add("SEMPosY", "SEMPosY");
  321. }
  322. if (strs[i] == "Area")
  323. {
  324. keyValues.Add("Area", table["str21"].ToString());
  325. }
  326. if (strs[i] == "EquivalentCircleDiameter")
  327. {
  328. keyValues.Add("Equivalent", table["str22"].ToString());
  329. }
  330. if (strs[i] == "MaxDiameter")
  331. {
  332. keyValues.Add("DMAX", table["str23"].ToString());
  333. }
  334. if (strs[i] == "MinDiameter")
  335. {
  336. keyValues.Add("DMIN", table["str24"].ToString());
  337. }
  338. if (strs[i] == "DiameterRatio")
  339. {
  340. keyValues.Add("DiameterRatio", table["str25"].ToString());
  341. }
  342. if (strs[i] == "FerretDiameter")
  343. {
  344. keyValues.Add("DFERET", table["str26"].ToString());
  345. }
  346. if (strs[i] == "PERP")
  347. {
  348. keyValues.Add("DPERP", table["str27"].ToString());
  349. }
  350. if (strs[i] == "PERI")
  351. {
  352. keyValues.Add("PERIMETER", table["str28"].ToString());
  353. }
  354. if (strs[i] == "INSCR")
  355. {
  356. keyValues.Add("DINSCR", table["str29"].ToString());
  357. }
  358. if (strs[i] == "MEAN")
  359. {
  360. keyValues.Add("DMEAN", table["str30"].ToString());
  361. }
  362. if (strs[i] == "ELONG")
  363. {
  364. keyValues.Add("DELONG", table["str31"].ToString());
  365. }
  366. if (strs[i] == "ASPECT_ELONG")
  367. {
  368. keyValues.Add("ASPECT_ELONG", table["str32"].ToString());
  369. }
  370. if (strs[i] == "Orientation")
  371. {
  372. keyValues.Add("ORIENTATION", table["str33"].ToString());
  373. }
  374. }
  375. keyValues.Add("Element", "Element");
  376. Dictionary<string, string>.Enumerator en = keyValues.GetEnumerator();
  377. for (int irow = 0; irow < keyValues.Count; irow++)
  378. {
  379. if (en.MoveNext())
  380. {
  381. if (en.Current.Key == "ParticleImage")
  382. {
  383. DataGridViewImageColumn iconColumn = new DataGridViewImageColumn();
  384. iconColumn.Name = en.Current.Key;
  385. iconColumn.HeaderText = en.Current.Value;
  386. dgV_Traceablilty.Columns.Add(iconColumn);
  387. }
  388. else if (en.Current.Key == "Element")
  389. {
  390. }
  391. else
  392. {
  393. int columndid = dgV_Traceablilty.Columns.Add(en.Current.Key, en.Current.Value);
  394. }
  395. }
  396. }
  397. //获取需要显示的元素名
  398. List<string> ElementTypeSort = new List<string>(sElementsColName.Split(',').ToList());//去重
  399. for (int i = 0; i < ElementTypeSort.Count; i++)
  400. {
  401. dgV_Traceablilty.Columns.Add(ElementTypeSort[i], ElementTypeSort[i]);
  402. }
  403. #endregion
  404. }
  405. /// <summary>
  406. /// 设置DataGridView样式
  407. /// </summary>
  408. private void SetDataGridViewStyle()
  409. {
  410. //用户不能调整标题的高度
  411. dgV_Traceablilty.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
  412. //用户不能调整 行高
  413. dgV_Traceablilty.AllowUserToResizeRows = false;
  414. //点击选择整行
  415. dgV_Traceablilty.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
  416. //居中显示
  417. System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
  418. dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
  419. dgV_Traceablilty.DefaultCellStyle = dataGridViewCellStyle1;
  420. dgV_Traceablilty.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
  421. //再次重覆禁用拖动表头高度,居然有效果了
  422. dgV_Traceablilty.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
  423. //设置grid可以复制
  424. dgV_Traceablilty.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
  425. //设置每列的宽度
  426. dgV_Traceablilty.Columns[0].Width = 40;//第一列序号的宽度设置一下吧,要不太丑
  427. dgV_Traceablilty.Columns[1].Width = 150;
  428. //dgV_Traceablilty.Columns[dgV_Traceablilty.Columns.Count - 1].Width = 450;
  429. //dgV_Traceablilty.Columns[dgV_Traceablilty.Columns.Count - 1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
  430. //设置序号列不排序
  431. dgV_Traceablilty.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
  432. //设置序号列不可以设置宽度
  433. dgV_Traceablilty.Columns[0].Resizable = DataGridViewTriState.False;
  434. dgV_Traceablilty.RowsDefaultCellStyle.BackColor = Color.Azure;
  435. }
  436. private void InclusionsTraceability_Resize(object sender, EventArgs e)
  437. {
  438. //控件随窗体全屏显示
  439. float[] scale = (float[])Tag;
  440. int i = 2;
  441. foreach (Control ctrl in this.Controls)
  442. {
  443. ctrl.Left = (int)(Size.Width * scale[i++]);
  444. ctrl.Top = (int)(Size.Height * scale[i++]);
  445. ctrl.Width = (int)(Size.Width / (float)scale[0] * ((Size)ctrl.Tag).Width);
  446. ctrl.Height = (int)(Size.Height / (float)scale[1] * ((Size)ctrl.Tag).Height);
  447. }
  448. }
  449. private void ExportExecl_Click(object sender, EventArgs e)
  450. {
  451. //将所有的数据导出到EXCEL中
  452. SaveFileDialog sfd = new SaveFileDialog();
  453. sfd.Filter = "Excel File(*.xlsx)|*.xlsx";
  454. //设置默认文件类型显示顺序
  455. sfd.FilterIndex = 1;
  456. sfd.FileName = "ParticlesInfo";
  457. //保存对话框是否记忆上次打开的目录
  458. sfd.RestoreDirectory = true;
  459. if (sfd.ShowDialog() == DialogResult.OK)
  460. {
  461. //IWorkbook workbook = new HSSFWorkbook(); //用于创建.xls office2003开始以前的
  462. IWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(); //用于创建.xlsx office2007开始以后的
  463. ISheet sheet;
  464. //创建Excel文件
  465. FileStream fs = File.Create(sfd.FileName);
  466. fs.Close();
  467. sheet = workbook.CreateSheet("Particles");//创建工作表
  468. //创建表格边框样式风格
  469. ICellStyle cellStyle = workbook.CreateCellStyle();
  470. cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
  471. cellStyle.VerticalAlignment = VerticalAlignment.Center;
  472. //设置上4边
  473. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  474. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  475. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  476. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  477. //设置字符大小和颜色
  478. IFont font = workbook.CreateFont();
  479. font.FontName = "黑体";
  480. font.FontHeightInPoints = 10;
  481. cellStyle.SetFont(font);
  482. //设置颗粒名列宽
  483. sheet.SetColumnWidth(1, 30 * 256);//夹杂物名列宽
  484. sheet.SetColumnWidth(2, 7 * 256);//图像列宽
  485. IRow row;
  486. ICell cell;
  487. //插入表头
  488. row = sheet.CreateRow(1);//从第15行添加一行
  489. row.Height = 30 * 20;
  490. for (int i_cell = 0; i_cell < dgV_Traceablilty.Columns.Count; i_cell++)
  491. {
  492. cell = row.CreateCell(i_cell);
  493. cell.CellStyle = cellStyle;
  494. cell.SetCellValue(dgV_Traceablilty.Columns[i_cell].Name);
  495. }
  496. //插入表内容
  497. for (int i_row = 0; i_row < dgV_Traceablilty.Rows.Count; i_row++)
  498. {
  499. row = sheet.CreateRow(2 + i_row);
  500. row.Height = 45 * 20;
  501. for (int i_cell = 0; i_cell < dgV_Traceablilty.Columns.Count; i_cell++)
  502. {
  503. cell = row.CreateCell(i_cell);
  504. cell.CellStyle = cellStyle;
  505. if (dgV_Traceablilty[i_cell, i_row].Value == null)
  506. continue;
  507. if (i_cell == 2)
  508. {
  509. //颗粒图像列
  510. Bitmap bp = (Bitmap)dgV_Traceablilty.Rows[i_row].Cells[2].Value;
  511. byte[] bytes = ImageConvertToBytes(bp);
  512. //第二步,将图片添加到workbook中,指定图片的格式,返回图片所在workbook->paicture数组中的索引的地址,从1开始
  513. int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
  514. //第三步,在sheet中创建画布
  515. IDrawing patriarch = sheet.CreateDrawingPatriarch();
  516. //第四步,设置锚点,(在起始单元格的X坐标0-1023,Y的坐标0-255,在终止单元格的X坐标0-1023,Y的坐标0-255,起始单元格行数,列数,终止单元格行数,列数)
  517. IClientAnchor anchor = patriarch.CreateAnchor(1, 1, 2, 2, i_cell, i_row + 2, i_cell + 1, i_row + 3);//终止比开始位置大1,会自动缩放到一个单元格内的
  518. //第五步,创建图片
  519. IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);
  520. //图像效果不好,自己另外导出吧,这里对该列宽进行了设置0
  521. }
  522. else
  523. {
  524. //非图像列
  525. double dbl = 0;
  526. if (double.TryParse(dgV_Traceablilty[i_cell, i_row].Value.ToString(), out dbl))
  527. {
  528. cell.SetCellValue(dbl);
  529. }
  530. else
  531. {
  532. cell.SetCellValue(dgV_Traceablilty[i_cell, i_row].Value.ToString());
  533. }
  534. }
  535. }
  536. }
  537. //完成后,对Excel进行保存
  538. FileStream file = new FileStream(sfd.FileName, FileMode.Create);
  539. workbook.Write(file);
  540. file.Close();
  541. MessageBox.Show("Export complete!");
  542. //导出完成后,打开Excel文件
  543. if (File.Exists(sfd.FileName))
  544. {
  545. //打开刚才导出的文件
  546. System.Diagnostics.Process.Start(sfd.FileName);
  547. }
  548. }
  549. }
  550. /// <summary>
  551. /// 将image转成bytes
  552. /// </summary>
  553. /// <param name="in_img"></param>
  554. /// <returns></returns>
  555. public byte[] ImageConvertToBytes(System.Drawing.Image in_img)
  556. {
  557. MemoryStream ms = new MemoryStream();
  558. in_img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  559. return ms.ToArray();
  560. }
  561. void CreateChart(IDrawing drawing, ISheet sheet, IClientAnchor anchor, int rowid)
  562. {
  563. var chart = drawing.CreateChart(anchor) as XSSFChart;
  564. //图表
  565. var data = chart.ChartDataFactory.CreateLineChartData<double, double>(); //折线图
  566. IChartAxis bottomAxis = chart.ChartAxisFactory.CreateCategoryAxis(AxisPosition.Bottom);
  567. IValueAxis leftAxis = chart.ChartAxisFactory.CreateValueAxis(AxisPosition.Left);
  568. leftAxis.Crosses = AxisCrosses.AutoZero;
  569. leftAxis.IsVisible = true;
  570. bottomAxis.IsVisible = true;
  571. //数据源
  572. IChartDataSource<double> ys = DataSources.FromNumericCellRange(sheet, new CellRangeAddress(rowid, rowid, 1, 2001));
  573. Double[] doubles = new Double[2000];
  574. for (int i = 0; i < 2000; i++)
  575. {
  576. doubles[i] = i;
  577. }
  578. IChartDataSource<double> xs = DataSources.FromArray(doubles);
  579. //数据系列
  580. var s1 = data.AddSeries(xs, ys);
  581. // 开始绘制折线图
  582. chart.Plot(data, bottomAxis, leftAxis);
  583. }
  584. private void 复制全部ToolStripMenuItem_Click(object sender, EventArgs e)
  585. {
  586. //复制整个表
  587. CopyAll();
  588. }
  589. /// <summary>
  590. /// 复制所有
  591. /// </summary>
  592. public void CopyAll()
  593. {
  594. dgV_Traceablilty.SelectAll();
  595. Clipboard.SetDataObject(dgV_Traceablilty.GetClipboardContent());
  596. }
  597. private void CopySelectToolStripMenuItem1_Click(object sender, EventArgs e)
  598. {
  599. //复制选择区域
  600. CopySelected();
  601. }
  602. /// <summary>
  603. /// 复制选择区域
  604. /// </summary>
  605. public void CopySelected()
  606. {
  607. //复制选择区域
  608. object oo = dgV_Traceablilty.GetClipboardContent();
  609. if (oo != null)
  610. Clipboard.SetDataObject(dgV_Traceablilty.GetClipboardContent());
  611. }
  612. private void 复制图像ToolStripMenuItem_Click(object sender, EventArgs e)
  613. {
  614. //对gridview进行截图
  615. CopyImage();
  616. }
  617. /// <summary>
  618. /// 以图像的方式将GridView进行截图
  619. /// </summary>
  620. public void CopyImage()
  621. {
  622. int height, width;
  623. width = dgV_Traceablilty.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) + 2;
  624. height = this.Height;
  625. Bitmap image = new Bitmap(width, height);
  626. dgV_Traceablilty.DrawToBitmap(image, new Rectangle(0, 0, width, height));
  627. Clipboard.SetImage(image);
  628. }
  629. }
  630. }