OTSInclusionsTraceability.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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. lan = new Language(this);
  55. table = lan.GetNameTable(this.Name);
  56. comboBox_SourceType.Items.Add(table["str1"]);
  57. comboBox_SourceType.Items.Add(table["str2"]);
  58. //comboBox_SourceType.Items.Add("精炼渣+耐材");
  59. comboBox_SourceType.SelectedIndex = 0;
  60. Init();
  61. tB_EquivalentCircularDiameter.Text = sEquivalentCircularDiameter;
  62. cB_contain.Checked = bContains;
  63. switch(sDisplaySource)
  64. {
  65. case "精炼渣": comboBox_SourceType.SelectedIndex = 0;break;
  66. case "耐材": comboBox_SourceType.SelectedIndex = 1; break;
  67. case "精炼渣+耐材": comboBox_SourceType.SelectedIndex = 2; break;
  68. case "Refining slag": comboBox_SourceType.SelectedIndex = 0; break;
  69. case "Refractory material": comboBox_SourceType.SelectedIndex = 1; break;
  70. case "Refining slag+Refractory material": comboBox_SourceType.SelectedIndex = 2; break;
  71. }
  72. #region 界面缩放控件位置记录
  73. int count = this.Controls.Count * 2 + 2;
  74. float[] nature = new float[count];
  75. int i = 0;
  76. nature[i++] = Size.Width;
  77. nature[i++] = Size.Height;
  78. foreach (Control ctrl in this.Controls)
  79. {
  80. nature[i++] = ctrl.Location.X / (float)Size.Width;
  81. nature[i++] = ctrl.Location.Y / (float)Size.Height;
  82. ctrl.Tag = ctrl.Size;
  83. }
  84. Tag = nature;
  85. #endregion
  86. tB_EquivalentCircularDiameter.Select(tB_EquivalentCircularDiameter.Text.Length, 0);
  87. }
  88. string AuquireEquCircleDiameter()
  89. {
  90. string condition = "";
  91. double EquCircleDiameter = 0;
  92. if (double.TryParse(tB_EquivalentCircularDiameter.Text,out EquCircleDiameter))
  93. {
  94. double Darea = Math.PI * (EquCircleDiameter * EquCircleDiameter / 4);
  95. if(cB_contain.Checked)
  96. {
  97. condition = "Area>=" + Darea.ToString();
  98. }
  99. else
  100. {
  101. condition = "Area>" + Darea.ToString();
  102. }
  103. }
  104. return condition;
  105. }
  106. /// <summary>
  107. /// DataRow转换为DataTable
  108. /// </summary>
  109. /// <param name="dt"></param>
  110. /// <param name="strWhere">筛选的条件</param>
  111. /// <returns></returns>
  112. public DataTable SreeenDataTable(DataTable dt, string strWhere)
  113. {
  114. if (dt.Rows.Count <= 0) return dt; //当数据为空时返回
  115. DataTable dtNew = dt.Clone(); //复制数据源的表结构
  116. DataRow[] dr = dt.Select(strWhere); //strWhere条件筛选出需要的数据!
  117. for (int i = 0; i < dr.Length; i++)
  118. {
  119. dtNew.Rows.Add(dr[i].ItemArray); // 将DataRow添加到DataTable中
  120. }
  121. return dtNew;
  122. }
  123. private void bn_Find_Click(object sender, EventArgs e)
  124. {
  125. string condition = AuquireEquCircleDiameter();
  126. if (condition == "")
  127. {
  128. MessageBox.Show("Please enter valid data!");
  129. return;
  130. }
  131. if(comboBox_SourceType.SelectedIndex==(int)SourceType.RefiningSlag)
  132. {
  133. condition += " and TypeName Like \'%CaO%\' ";
  134. }
  135. else if(comboBox_SourceType.SelectedIndex == (int)SourceType.Refractory)
  136. {
  137. condition += " and (TypeName Like \'%MgO%\' or TypeName Like \'%Al2O3%\')";
  138. }
  139. else
  140. {
  141. condition += " and (TypeName Like \'%MgO%\' or TypeName Like \'%Al2O3%\' or TypeName Like \'%CaO%\')";
  142. }
  143. particlesDisplay = SreeenDataTable(particles, condition);
  144. DataTable elementchemistry = dataOperation.GetElementChemistry();
  145. for (int i = 0; i < particlesDisplay.Rows.Count; i++)
  146. {
  147. string str = "XRayId = " + particlesDisplay.Rows[i]["particleId"].ToString() + " and fieldid = " + particlesDisplay.Rows[i]["fieldid"].ToString();
  148. DataRow[] drs = elementchemistry.Select(str);
  149. string ConcatenatedString = "";
  150. for (int j = 0; j < drs.Length; j++)
  151. {
  152. ConcatenatedString += drs[j]["name"] + "-" + drs[j]["Percentage"] + ';';
  153. }
  154. particlesDisplay.Rows[i]["Element"] = ConcatenatedString;
  155. }
  156. BindDataGridView();
  157. SetDataGridViewStyle();
  158. dataOperation.WriteXmlDefaultData(tB_EquivalentCircularDiameter.Text, cB_contain.Checked,(comboBox_SourceType.SelectedItem).ToString());
  159. }
  160. void BindDataGridView()
  161. {
  162. dgV_Traceablilty.Visible = false;
  163. this.Cursor = Cursors.WaitCursor;
  164. if (particlesDisplay== null)
  165. {
  166. return;
  167. }
  168. dgV_Traceablilty.Rows.Clear();
  169. //获取需要显示的元素名
  170. List<string> ElementTypeSort = new List<string>(sElementsColName.Split(',').ToList());//去重
  171. //double jd = 95f / (double)particles.Rows.Count;//计算进度刻度
  172. string filePath = "";
  173. if (RetDBAddress.Contains("db"))
  174. {
  175. filePath = Directory.GetParent(RetDBAddress).FullName+"\\";
  176. }
  177. else
  178. {
  179. filePath = RetDBAddress + "\\FIELD_FILES\\";
  180. }
  181. KeyValuePair<string, Bitmap> FieldImage = new KeyValuePair<string, Bitmap>();
  182. for (int i = 0; i < particlesDisplay.Rows.Count; i++)
  183. {
  184. //更新进度,每100条记录加载完,更新一次进度
  185. //if (i % 10 == 0)
  186. // m_frm_userprogress.SetProgressValueAndText((int)(jd * i), "loading..");
  187. Dictionary<string, string>.Enumerator enl = keyValues.GetEnumerator();
  188. int add_rowindex = dgV_Traceablilty.Rows.Add();
  189. dgV_Traceablilty.Rows[add_rowindex].Cells[0].Value = (add_rowindex + 1).ToString();
  190. for (int k = 0; k < keyValues.Count; k++)
  191. {
  192. if (enl.MoveNext())
  193. {
  194. if (enl.Current.Key == "rowid")
  195. {
  196. //dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = i + 1;
  197. }
  198. if (enl.Current.Key == "ParticleImage")
  199. {
  200. if (FieldImage.Key != particlesDisplay.Rows[i]["fieldid"].ToString() || FieldImage.Value == null)
  201. {
  202. string imagePath = filePath + "Field" + particlesDisplay.Rows[i]["fieldid"].ToString() + ".bmp";
  203. FieldImage = new KeyValuePair<string, Bitmap>(particlesDisplay.Rows[i]["fieldid"].ToString(), dataOperation.ReadImageFile(imagePath));
  204. }
  205. 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"]) };
  206. Bitmap bmap = dataOperation.GetBitmapByParticle(FieldImage.Value, rectangle);
  207. 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() };
  208. dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = bmap;
  209. dgV_Traceablilty.Rows[add_rowindex].Height = bmap.Height + 20;
  210. }
  211. //if (enl.Current.Key == "SourceType")
  212. //{
  213. // if (particlesDisplay.Rows[i]["TypeName"].ToString().Contains("CaO"))
  214. // {
  215. // dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = SourceType.RefiningSlag.ToString();
  216. // }
  217. // else
  218. // {
  219. // dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = SourceType.Refractory.ToString();
  220. // }
  221. //}
  222. if (enl.Current.Key == "DiameterRatio")
  223. {
  224. double d = Convert.ToDouble(particlesDisplay.Rows[i]["DMAX"]) / Convert.ToDouble(particlesDisplay.Rows[i]["DMIN"]);
  225. dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = Math.Round(d, 2);
  226. }
  227. if (enl.Current.Key == "ASPECT_ELONG")
  228. {
  229. double d = Convert.ToDouble(particlesDisplay.Rows[i]["DELONG"]) / Convert.ToDouble(particlesDisplay.Rows[i]["DMEAN"]);
  230. dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = Math.Round(d, 2);
  231. }
  232. if (particlesDisplay.Columns.Contains(enl.Current.Key))
  233. {
  234. double num = 0;
  235. if (double.TryParse(particlesDisplay.Rows[i][enl.Current.Key].ToString(), out num))
  236. {
  237. dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = Math.Round(num, 2);
  238. }
  239. else if (enl.Current.Key == "Element")
  240. {
  241. List<string> elementtemp = new List<string>(ElementTypeSort);
  242. string[] strcbo = particlesDisplay.Rows[i][enl.Current.Key].ToString().Split(';');
  243. for (int j = 0; j < strcbo.Length; j++)
  244. {
  245. string[] str = strcbo[j].Split('-');
  246. if (ElementTypeSort.Contains(str[0]))
  247. { dgV_Traceablilty.Rows[add_rowindex].Cells[str[0].ToString()].Value = Math.Round(double.Parse(str[1]), 2).ToString(); }
  248. elementtemp.Remove(str[0].ToString());
  249. }
  250. foreach (var ele in elementtemp)
  251. {
  252. dgV_Traceablilty.Rows[add_rowindex].Cells[ele].Value = "0";
  253. }
  254. }
  255. else
  256. {
  257. dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = particlesDisplay.Rows[i][enl.Current.Key];
  258. }
  259. }
  260. //if (enl.Current.Key == "TypeName")
  261. //{
  262. // if (particlesDisplay.Rows[i]["TypeId"].ToString() == "9")
  263. // {
  264. // dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = "Not Identified";
  265. // }
  266. //}
  267. if (enl.Current.Key == "Equivalent")
  268. {
  269. double dSize = Convert.ToDouble(particlesDisplay.Rows[i]["Area"]);
  270. double Diameter = Math.Sqrt(dSize / Math.PI) * 2;
  271. dgV_Traceablilty.Rows[add_rowindex].Cells[k].Value = Math.Round(Diameter, 2);
  272. }
  273. }
  274. }
  275. }
  276. #region 加载进度条进度部份结束
  277. //加载完成设置鼠标为默认
  278. this.Cursor = Cursors.Default;
  279. //string str8 = table["str8"].ToString();
  280. //m_frm_userprogress.SetProgressValueAndText(100, str8);
  281. ////加载完成,关闭进度条
  282. //m_frm_userprogress.Close();
  283. #endregion
  284. dgV_Traceablilty.Visible = true;
  285. }
  286. void Init()
  287. {
  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. //获取需要显示的元素名
  401. List<string> ElementTypeSort = new List<string>(sElementsColName.Split(',').ToList());//去重
  402. for (int i = 0; i < ElementTypeSort.Count; i++)
  403. {
  404. dgV_Traceablilty.Columns.Add(ElementTypeSort[i], ElementTypeSort[i]);
  405. }
  406. #endregion
  407. }
  408. /// <summary>
  409. /// 设置DataGridView样式
  410. /// </summary>
  411. private void SetDataGridViewStyle()
  412. {
  413. //用户不能调整标题的高度
  414. dgV_Traceablilty.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
  415. //用户不能调整 行高
  416. dgV_Traceablilty.AllowUserToResizeRows = false;
  417. //点击选择整行
  418. dgV_Traceablilty.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
  419. //居中显示
  420. System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
  421. dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
  422. dgV_Traceablilty.DefaultCellStyle = dataGridViewCellStyle1;
  423. dgV_Traceablilty.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
  424. //再次重覆禁用拖动表头高度,居然有效果了
  425. dgV_Traceablilty.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
  426. //设置grid可以复制
  427. dgV_Traceablilty.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
  428. //设置每列的宽度
  429. dgV_Traceablilty.Columns[0].Width = 40;//第一列序号的宽度设置一下吧,要不太丑
  430. dgV_Traceablilty.Columns[1].Width = 150;
  431. //dgV_Traceablilty.Columns[dgV_Traceablilty.Columns.Count - 1].Width = 450;
  432. //dgV_Traceablilty.Columns[dgV_Traceablilty.Columns.Count - 1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
  433. //设置序号列不排序
  434. dgV_Traceablilty.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
  435. //设置序号列不可以设置宽度
  436. dgV_Traceablilty.Columns[0].Resizable = DataGridViewTriState.False;
  437. dgV_Traceablilty.RowsDefaultCellStyle.BackColor = Color.Azure;
  438. }
  439. private void InclusionsTraceability_Resize(object sender, EventArgs e)
  440. {
  441. }
  442. private void ExportExecl_Click(object sender, EventArgs e)
  443. {
  444. //将所有的数据导出到EXCEL中
  445. SaveFileDialog sfd = new SaveFileDialog();
  446. sfd.Filter = "Excel File(*.xlsx)|*.xlsx";
  447. //设置默认文件类型显示顺序
  448. sfd.FilterIndex = 1;
  449. sfd.FileName = "ParticlesInfo";
  450. //保存对话框是否记忆上次打开的目录
  451. sfd.RestoreDirectory = true;
  452. if (sfd.ShowDialog() == DialogResult.OK)
  453. {
  454. //IWorkbook workbook = new HSSFWorkbook(); //用于创建.xls office2003开始以前的
  455. IWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(); //用于创建.xlsx office2007开始以后的
  456. ISheet sheet;
  457. //创建Excel文件
  458. FileStream fs = File.Create(sfd.FileName);
  459. fs.Close();
  460. sheet = workbook.CreateSheet("Particles");//创建工作表
  461. //创建表格边框样式风格
  462. ICellStyle cellStyle = workbook.CreateCellStyle();
  463. cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
  464. cellStyle.VerticalAlignment = VerticalAlignment.Center;
  465. //设置上4边
  466. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  467. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  468. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  469. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  470. //设置字符大小和颜色
  471. IFont font = workbook.CreateFont();
  472. font.FontName = "黑体";
  473. font.FontHeightInPoints = 10;
  474. cellStyle.SetFont(font);
  475. //设置颗粒名列宽
  476. sheet.SetColumnWidth(1, 30 * 256);//夹杂物名列宽
  477. sheet.SetColumnWidth(2, 7 * 256);//图像列宽
  478. IRow row;
  479. ICell cell;
  480. //插入表头
  481. row = sheet.CreateRow(1);//从第15行添加一行
  482. row.Height = 30 * 20;
  483. for (int i_cell = 0; i_cell < dgV_Traceablilty.Columns.Count; i_cell++)
  484. {
  485. cell = row.CreateCell(i_cell);
  486. cell.CellStyle = cellStyle;
  487. cell.SetCellValue(dgV_Traceablilty.Columns[i_cell].Name);
  488. }
  489. //插入表内容
  490. for (int i_row = 0; i_row < dgV_Traceablilty.Rows.Count; i_row++)
  491. {
  492. row = sheet.CreateRow(2 + i_row);
  493. row.Height = 45 * 20;
  494. for (int i_cell = 0; i_cell < dgV_Traceablilty.Columns.Count; i_cell++)
  495. {
  496. cell = row.CreateCell(i_cell);
  497. cell.CellStyle = cellStyle;
  498. if (dgV_Traceablilty[i_cell, i_row].Value == null)
  499. continue;
  500. if (i_cell == 2)
  501. {
  502. //颗粒图像列
  503. Bitmap bp = (Bitmap)dgV_Traceablilty.Rows[i_row].Cells[2].Value;
  504. byte[] bytes = ImageConvertToBytes(bp);
  505. //第二步,将图片添加到workbook中,指定图片的格式,返回图片所在workbook->paicture数组中的索引的地址,从1开始
  506. int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
  507. //第三步,在sheet中创建画布
  508. IDrawing patriarch = sheet.CreateDrawingPatriarch();
  509. //第四步,设置锚点,(在起始单元格的X坐标0-1023,Y的坐标0-255,在终止单元格的X坐标0-1023,Y的坐标0-255,起始单元格行数,列数,终止单元格行数,列数)
  510. IClientAnchor anchor = patriarch.CreateAnchor(1, 1, 2, 2, i_cell, i_row + 2, i_cell + 1, i_row + 3);//终止比开始位置大1,会自动缩放到一个单元格内的
  511. //第五步,创建图片
  512. IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);
  513. //图像效果不好,自己另外导出吧,这里对该列宽进行了设置0
  514. }
  515. else
  516. {
  517. //非图像列
  518. double dbl = 0;
  519. if (double.TryParse(dgV_Traceablilty[i_cell, i_row].Value.ToString(), out dbl))
  520. {
  521. cell.SetCellValue(dbl);
  522. }
  523. else
  524. {
  525. cell.SetCellValue(dgV_Traceablilty[i_cell, i_row].Value.ToString());
  526. }
  527. }
  528. }
  529. }
  530. //完成后,对Excel进行保存
  531. FileStream file = new FileStream(sfd.FileName, FileMode.Create);
  532. workbook.Write(file);
  533. file.Close();
  534. MessageBox.Show("Export complete!");
  535. //导出完成后,打开Excel文件
  536. if (File.Exists(sfd.FileName))
  537. {
  538. //打开刚才导出的文件
  539. System.Diagnostics.Process.Start(sfd.FileName);
  540. }
  541. }
  542. }
  543. /// <summary>
  544. /// 将image转成bytes
  545. /// </summary>
  546. /// <param name="in_img"></param>
  547. /// <returns></returns>
  548. public byte[] ImageConvertToBytes(System.Drawing.Image in_img)
  549. {
  550. MemoryStream ms = new MemoryStream();
  551. in_img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  552. return ms.ToArray();
  553. }
  554. void CreateChart(IDrawing drawing, ISheet sheet, IClientAnchor anchor, int rowid)
  555. {
  556. var chart = drawing.CreateChart(anchor) as XSSFChart;
  557. //图表
  558. var data = chart.ChartDataFactory.CreateLineChartData<double, double>(); //折线图
  559. IChartAxis bottomAxis = chart.ChartAxisFactory.CreateCategoryAxis(AxisPosition.Bottom);
  560. IValueAxis leftAxis = chart.ChartAxisFactory.CreateValueAxis(AxisPosition.Left);
  561. leftAxis.Crosses = AxisCrosses.AutoZero;
  562. leftAxis.IsVisible = true;
  563. bottomAxis.IsVisible = true;
  564. //数据源
  565. IChartDataSource<double> ys = DataSources.FromNumericCellRange(sheet, new CellRangeAddress(rowid, rowid, 1, 2001));
  566. Double[] doubles = new Double[2000];
  567. for (int i = 0; i < 2000; i++)
  568. {
  569. doubles[i] = i;
  570. }
  571. IChartDataSource<double> xs = DataSources.FromArray(doubles);
  572. //数据系列
  573. var s1 = data.AddSeries(xs, ys);
  574. // 开始绘制折线图
  575. chart.Plot(data, bottomAxis, leftAxis);
  576. }
  577. private void 复制全部ToolStripMenuItem_Click(object sender, EventArgs e)
  578. {
  579. //复制整个表
  580. CopyAll();
  581. }
  582. /// <summary>
  583. /// 复制所有
  584. /// </summary>
  585. public void CopyAll()
  586. {
  587. dgV_Traceablilty.SelectAll();
  588. Clipboard.SetDataObject(dgV_Traceablilty.GetClipboardContent());
  589. }
  590. private void CopySelectToolStripMenuItem1_Click(object sender, EventArgs e)
  591. {
  592. //复制选择区域
  593. CopySelected();
  594. }
  595. /// <summary>
  596. /// 复制选择区域
  597. /// </summary>
  598. public void CopySelected()
  599. {
  600. //复制选择区域
  601. object oo = dgV_Traceablilty.GetClipboardContent();
  602. if (oo != null)
  603. Clipboard.SetDataObject(dgV_Traceablilty.GetClipboardContent());
  604. }
  605. private void 复制图像ToolStripMenuItem_Click(object sender, EventArgs e)
  606. {
  607. //对gridview进行截图
  608. CopyImage();
  609. }
  610. /// <summary>
  611. /// 以图像的方式将GridView进行截图
  612. /// </summary>
  613. public void CopyImage()
  614. {
  615. int height, width;
  616. width = dgV_Traceablilty.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) + 2;
  617. height = this.Height;
  618. Bitmap image = new Bitmap(width, height);
  619. dgV_Traceablilty.DrawToBitmap(image, new Rectangle(0, 0, width, height));
  620. Clipboard.SetImage(image);
  621. }
  622. }
  623. }