OTSInclusionsTraceability.cs 30 KB

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