You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1304 lines
55 KiB

3 weeks ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Web;
  9. using System.Web.UI;
  10. using System.Web.UI.WebControls;
  11. using NFine.Code.Excel;
  12. using Aspose.Cells;
  13. using NPOI.HSSF.UserModel;
  14. using NPOI.SS.UserModel;
  15. using NPOI.HPSF;
  16. using System.Drawing;
  17. using NPOI.XSSF.UserModel;
  18. using NPOI.SS.Formula.Functions;
  19. namespace NFine.Code
  20. {
  21. public class ExcelHelper
  22. {
  23. /// <summary>
  24. /// 导出数据到EXCEL文件
  25. /// </summary>
  26. /// <param name="page">页面</param>
  27. /// <param name="gvExcel">导出的GrivView</param>
  28. public static void ExportToExcel(System.Web.UI.Page page, GridView dgExcel, HttpResponse Response, string fileName)
  29. {
  30. try
  31. {
  32. fileName = fileName + ".xls";
  33. page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
  34. Response.Clear();
  35. Response.Buffer = true;
  36. Response.Charset = "utf-8";
  37. Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
  38. Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
  39. Response.ContentType = "application/ms-excel";
  40. dgExcel.Page.EnableViewState = false;
  41. System.IO.StringWriter tw = new System.IO.StringWriter();
  42. System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
  43. dgExcel.RenderControl(hw);
  44. // 输出DataGrid内容
  45. Response.Write(tw.ToString());
  46. Response.End();
  47. }
  48. catch (Exception ex)
  49. {
  50. throw ex;
  51. }
  52. }
  53. }
  54. /// <summary>
  55. /// 导出EXCEL
  56. /// </summary>
  57. public class GridViewExportUtil
  58. {
  59. /// <summary>
  60. /// 将GRIDVIEW导出excel
  61. /// </summary>
  62. /// <param name="fileName">excel文件名</param>
  63. /// <param name="gv">GridView ID</param>
  64. public static void Export(GridView gv, string PreSellNo)
  65. {
  66. //dataGridView1.Columns[0].HeaderText 循环列判断是否要设置为数字类型
  67. List<int> list = new List<int>();
  68. int k = 0; //序号
  69. int p = 0; //价格
  70. int a = 0; //数量
  71. int d = 0; //折扣
  72. for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
  73. {
  74. //if (gv.HeaderRow.Cells[i].Text.Contains("F_Id") || gv.HeaderRow.Cells[i].Text.Contains("Product_Id"))
  75. //{
  76. // list.Add(i);
  77. //}
  78. if (gv.HeaderRow.Cells[i].Text.Contains("No.") || gv.HeaderRow.Cells[i].Text.Contains("Finished Weight(ct)") ||
  79. gv.HeaderRow.Cells[i].Text.Contains("Rough Weight(ct)") || gv.HeaderRow.Cells[i].Text.Contains("Price(USD)") ||
  80. gv.HeaderRow.Cells[i].Text.Contains("Amount(USD)"))
  81. {
  82. list.Add(i);
  83. }
  84. //if (gv.HeaderRow.Cells[i].Text.Contains("No."))
  85. // k = i;
  86. if (gv.HeaderRow.Cells[i].Text.Contains("Price(USD)"))
  87. p = i;
  88. if (gv.HeaderRow.Cells[i].Text.Contains("Amount(USD)"))
  89. a = i;
  90. //if (gv.HeaderRow.Cells[i].Text.Contains("Discount(%)"))
  91. // d = i;
  92. }
  93. foreach (GridViewRow row in gv.Rows)
  94. {
  95. int j = 0;
  96. foreach (TableCell cell in row.Cells)
  97. {
  98. if (!list.Contains(j))
  99. {
  100. cell.Style.Add("vnd.ms-excel.numberformat", "@");//给表格内容设置样式
  101. } // end foreach (TableCell cell in row.Cells)
  102. else
  103. {
  104. if (j != 0)
  105. {
  106. if (j == p || j == a)
  107. cell.Style.Add("vnd.ms-excel.numberformat", "#,##0.00");
  108. //else if (j == d)
  109. // cell.Style.Add("vnd.ms-excel.numberformat", "#0%");
  110. else
  111. cell.Style.Add("vnd.ms-excel.numberformat", "#,##0.000");//保留三位小数的样式,否则为默认样式
  112. }
  113. }
  114. j++;
  115. }
  116. } // end foreach (GridViewRow row in dgExcel.Rows)
  117. HttpContext.Current.Response.Clear();
  118. string styleText = @"<style> .text{mso-number-format:\@;} </style> ";
  119. string fileName = "";
  120. if (!string.IsNullOrEmpty(PreSellNo))
  121. fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "-OrderNo[" + PreSellNo + "].xls";
  122. else
  123. fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
  124. HttpContext.Current.Response.AddHeader(
  125. "content-disposition", string.Format("attachment; filename={0}", fileName));
  126. HttpContext.Current.Response.ContentType = "application/ms-excel";
  127. HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
  128. using (StringWriter sw = new StringWriter())
  129. {
  130. using (HtmlTextWriter htw = new HtmlTextWriter(sw))
  131. {
  132. // Create a form to contain the grid
  133. Table table = new Table();
  134. table.GridLines = gv.GridLines;
  135. if (gv.HeaderRow != null)
  136. {
  137. GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
  138. table.Rows.Add(gv.HeaderRow);
  139. for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
  140. {
  141. table.Rows[0].Cells[i].BackColor = System.Drawing.Color.FromArgb(220, 240, 241);
  142. table.Rows[0].Cells[i].ForeColor = System.Drawing.Color.Black;
  143. table.Rows[0].Cells[i].Height = Unit.Pixel(24);
  144. }
  145. }
  146. // add each of the data rows to the table
  147. foreach (GridViewRow row in gv.Rows)
  148. {
  149. GridViewExportUtil.PrepareControlForExport(row);
  150. row.Height = Unit.Pixel(22);
  151. row.HorizontalAlign = HorizontalAlign.Center;
  152. table.Rows.Add(row);
  153. }
  154. // add the footer row to the table
  155. if (gv.FooterRow != null)
  156. {
  157. GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
  158. table.Rows.Add(gv.FooterRow);
  159. }
  160. #region 手动增加头部三行和底部一行
  161. #region ItemList表头行
  162. table.Rows.AddAt(0, new TableRow());
  163. table.Rows[0].Cells.Add(new TableCell());
  164. table.Rows[0].Cells[0].Text = "ITEMS LIST";
  165. table.Rows[0].Cells[0].Font.Bold = true;
  166. table.Rows[0].Cells[0].ColumnSpan = 9;
  167. table.Rows[0].Cells[0].BackColor = System.Drawing.Color.FromArgb(220, 240, 241);
  168. table.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Black;
  169. table.Rows[0].Cells[0].Height = Unit.Pixel(24);
  170. table.Rows[0].Cells[0].Font.Size = FontUnit.Parse("16");
  171. table.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
  172. table.Rows[0].Cells[0].BorderWidth = 0;
  173. table.Rows[0].BorderStyle = System.Web.UI.WebControls.BorderStyle.None;
  174. #endregion
  175. #region To S/C No 行
  176. table.Rows.AddAt(1, new TableRow());
  177. table.Rows[1].Cells.Add(new TableCell());
  178. table.Rows[1].Cells[0].Text = "TO:";
  179. table.Rows[1].Cells[0].Font.Bold = true;
  180. table.Rows[1].Cells[0].ColumnSpan = 4;
  181. table.Rows[1].Cells[0].HorizontalAlign = HorizontalAlign.Left;
  182. table.Rows[1].Cells[0].BorderWidth = 0;
  183. table.Rows[1].Cells.Add(new TableCell());
  184. table.Rows[1].Cells[1].Text = "";
  185. table.Rows[1].Cells[1].ColumnSpan = 2;
  186. table.Rows[1].Cells[1].BorderWidth = 0;
  187. table.Rows[1].Cells.Add(new TableCell());
  188. table.Rows[1].Cells[2].Text = "S/C NO:";
  189. table.Rows[1].Cells[2].Font.Bold = true;
  190. table.Rows[1].Cells[2].ColumnSpan = 3;
  191. table.Rows[1].Cells[2].HorizontalAlign = HorizontalAlign.Left;
  192. table.Rows[1].Cells[2].BorderWidth = 0;
  193. #endregion
  194. #region Date 行
  195. table.Rows.AddAt(2, new TableRow());
  196. table.Rows[2].Cells.Add(new TableCell());
  197. table.Rows[2].Cells[0].Text = "";
  198. table.Rows[2].Cells[0].ColumnSpan = 4;
  199. table.Rows[2].Cells[0].HorizontalAlign = HorizontalAlign.Left;
  200. table.Rows[2].Cells[0].BorderWidth = 0;
  201. table.Rows[2].Cells.Add(new TableCell());
  202. table.Rows[2].Cells[1].Text = "";
  203. table.Rows[2].Cells[1].ColumnSpan = 2;
  204. table.Rows[2].Cells[1].BorderWidth = 0;
  205. table.Rows[2].Cells.Add(new TableCell());
  206. table.Rows[2].Cells[2].Text = "DATE:" + DateTime.Now.ToString("yyyy-MM-dd");
  207. table.Rows[2].Cells[2].Font.Bold = true;
  208. table.Rows[2].Cells[2].ColumnSpan = 3;
  209. table.Rows[2].Cells[2].HorizontalAlign = HorizontalAlign.Left;
  210. table.Rows[2].Cells[2].BorderWidth = 0;
  211. #endregion
  212. #region Total 行
  213. table.Rows.Add(new TableRow());
  214. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  215. table.Rows[table.Rows.Count - 1].Cells[0].Text = "Total:";
  216. table.Rows[table.Rows.Count - 1].Cells[0].ColumnSpan = 2;
  217. table.Rows[table.Rows.Count - 1].Cells[0].HorizontalAlign = HorizontalAlign.Left;
  218. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  219. table.Rows[table.Rows.Count - 1].Cells[1].Text = "";
  220. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  221. table.Rows[table.Rows.Count - 1].Cells[2].Text = "";
  222. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  223. table.Rows[table.Rows.Count - 1].Cells[3].Text = "";
  224. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  225. table.Rows[table.Rows.Count - 1].Cells[4].Text = "";
  226. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  227. table.Rows[table.Rows.Count - 1].Cells[5].Text = "";
  228. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  229. table.Rows[table.Rows.Count - 1].Cells[6].Text = "";
  230. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  231. table.Rows[table.Rows.Count - 1].Cells[7].Text = "";
  232. #endregion
  233. #endregion
  234. //设置table整体字体样式和大小
  235. table.Font.Name = "宋体";
  236. table.Font.Size = FontUnit.Parse("9.5");
  237. // render the table into the htmlwriter
  238. table.RenderControl(htw);
  239. // render the htmlwriter into the response
  240. HttpContext.Current.Response.Write(sw.ToString());
  241. HttpContext.Current.Response.Write(styleText);
  242. HttpContext.Current.Response.End();
  243. }
  244. }
  245. }
  246. public static void Export2(GridView gv)
  247. {
  248. //dataGridView1.Columns[0].HeaderText 循环列判断是否要设置为数字类型
  249. List<int> list = new List<int>();
  250. int k = 0; //序号
  251. int p = 0; //价格
  252. for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
  253. {
  254. if (gv.HeaderRow.Cells[i].Text.Contains("No.") || gv.HeaderRow.Cells[i].Text.Contains("Finished Weight(ct)") ||
  255. gv.HeaderRow.Cells[i].Text.Contains("Rough Weight(ct)") || gv.HeaderRow.Cells[i].Text.Contains("Price(USD)")
  256. || gv.HeaderRow.Cells[i].Text.Contains("Qty"))
  257. {
  258. list.Add(i);
  259. }
  260. if (gv.HeaderRow.Cells[i].Text.Contains("Price(USD)"))
  261. p = i;
  262. }
  263. foreach (GridViewRow row in gv.Rows)
  264. {
  265. int j = 0;
  266. foreach (TableCell cell in row.Cells)
  267. {
  268. if (!list.Contains(j))
  269. {
  270. cell.Style.Add("vnd.ms-excel.numberformat", "@");//给表格内容设置样式
  271. } // end foreach (TableCell cell in row.Cells)
  272. else
  273. {
  274. if (j != 0)
  275. {
  276. if (j == p)
  277. cell.Style.Add("vnd.ms-excel.numberformat", "#,##0.00");
  278. else
  279. cell.Style.Add("vnd.ms-excel.numberformat", "#,##0.000");//保留三位小数的样式,否则为默认样式
  280. }
  281. }
  282. j++;
  283. }
  284. } // end foreach (GridViewRow row in dgExcel.Rows)
  285. HttpContext.Current.Response.Clear();
  286. string styleText = @"<style> .text{mso-number-format:\@;} </style> ";
  287. string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
  288. HttpContext.Current.Response.AddHeader(
  289. "content-disposition", string.Format("attachment; filename={0}", fileName));
  290. HttpContext.Current.Response.ContentType = "application/ms-excel";
  291. HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
  292. using (StringWriter sw = new StringWriter())
  293. {
  294. using (HtmlTextWriter htw = new HtmlTextWriter(sw))
  295. {
  296. // Create a form to contain the grid
  297. Table table = new Table();
  298. table.GridLines = gv.GridLines;
  299. if (gv.HeaderRow != null)
  300. {
  301. GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
  302. table.Rows.Add(gv.HeaderRow);
  303. for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
  304. {
  305. table.Rows[0].Cells[i].BackColor = System.Drawing.Color.FromArgb(220, 240, 241);
  306. table.Rows[0].Cells[i].ForeColor = System.Drawing.Color.Black;
  307. table.Rows[0].Cells[i].Height = Unit.Pixel(24);
  308. }
  309. }
  310. // add each of the data rows to the table
  311. foreach (GridViewRow row in gv.Rows)
  312. {
  313. GridViewExportUtil.PrepareControlForExport(row);
  314. row.Height = Unit.Pixel(22);
  315. row.HorizontalAlign = HorizontalAlign.Center;
  316. table.Rows.Add(row);
  317. }
  318. // add the footer row to the table
  319. if (gv.FooterRow != null)
  320. {
  321. GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
  322. table.Rows.Add(gv.FooterRow);
  323. }
  324. //设置table整体字体样式和大小
  325. table.Font.Name = "宋体";
  326. table.Font.Size = FontUnit.Parse("9.5");
  327. // render the table into the htmlwriter
  328. table.RenderControl(htw);
  329. // render the htmlwriter into the response
  330. HttpContext.Current.Response.Write(sw.ToString());
  331. HttpContext.Current.Response.Write(styleText);
  332. HttpContext.Current.Response.End();
  333. }
  334. }
  335. }
  336. public static void Export(DataTable dt, string PreSellNo)
  337. {
  338. using (GridView gv = new GridView())
  339. {
  340. DataTable dtExport = new DataTable();
  341. dtExport.Columns.Add("No.", Type.GetType("System.Int32"));
  342. dtExport.Columns.Add("Product No.", Type.GetType("System.String"));
  343. dtExport.Columns.Add("Measurement", Type.GetType("System.String"));
  344. dtExport.Columns.Add("Finished Weight(ct)", Type.GetType("System.Decimal"));
  345. dtExport.Columns.Add("Rough Weight(ct)", Type.GetType("System.Decimal"));
  346. dtExport.Columns.Add("Price(USD)", Type.GetType("System.Decimal"));
  347. dtExport.Columns.Add("Discount(%)", Type.GetType("System.String"));
  348. dtExport.Columns.Add("Amount(USD)", Type.GetType("System.Decimal"));
  349. dtExport.Columns.Add("Shape", Type.GetType("System.String"));
  350. int number = 1;
  351. //for (int i = 0; i < 3; i++)
  352. //{
  353. // DataRow rtop = dtExport.NewRow();
  354. // dtExport.Rows.Add(rtop);
  355. //}
  356. foreach (DataRow row in dt.Rows)
  357. {
  358. DataRow r = dtExport.NewRow();
  359. r["No."] = number;
  360. r["Product No."] = row["ProductSN"].ToString();
  361. r["Measurement"] = row["Measurement"].ToString();
  362. r["Finished Weight(ct)"] = row["Weight"].ToString();
  363. r["Rough Weight(ct)"] = row["GrossWeight"].ToString();
  364. r["Price(USD)"] = string.IsNullOrEmpty(row["Price"].ToString()) ? 0 : decimal.Parse(row["Price"].ToString());
  365. r["Discount(%)"] = row["Discount"].ToString();
  366. r["Amount(USD)"] = string.IsNullOrEmpty(row["Amount"].ToString()) ? 0 : decimal.Parse(row["Amount"].ToString());
  367. r["Shape"] = row["Shape"].ToString();
  368. dtExport.Rows.Add(r);
  369. number++;
  370. }
  371. gv.DataSource = dtExport;
  372. gv.DataBind();
  373. Export(gv, PreSellNo);
  374. }
  375. }
  376. public static void Export2(DataTable dt)
  377. {
  378. using (GridView gv = new GridView())
  379. {
  380. DataTable dtExport = new DataTable();
  381. dtExport.Columns.Add("No.", Type.GetType("System.Int32"));
  382. dtExport.Columns.Add("Product No.", Type.GetType("System.String"));
  383. dtExport.Columns.Add("Measurement", Type.GetType("System.String"));
  384. dtExport.Columns.Add("Sort", Type.GetType("System.String"));
  385. dtExport.Columns.Add("Location", Type.GetType("System.String"));
  386. dtExport.Columns.Add("Qty", Type.GetType("System.Int32"));
  387. dtExport.Columns.Add("Finished Weight(ct)", Type.GetType("System.Decimal"));
  388. dtExport.Columns.Add("Rough Weight(ct)", Type.GetType("System.Decimal"));
  389. dtExport.Columns.Add("Price(USD)", Type.GetType("System.Decimal"));
  390. dtExport.Columns.Add("Shape", Type.GetType("System.String"));
  391. dtExport.Columns.Add("CertificateNo", Type.GetType("System.String"));
  392. dtExport.Columns.Add("Color", Type.GetType("System.String"));
  393. dtExport.Columns.Add("Clarity", Type.GetType("System.String"));
  394. dtExport.Columns.Add("Polish", Type.GetType("System.String"));
  395. int number = 1;
  396. foreach (DataRow row in dt.Rows)
  397. {
  398. DataRow r = dtExport.NewRow();
  399. r["No."] = number;
  400. r["Product No."] = row["ProductSN"].ToString();
  401. r["Measurement"] = row["Measurement"].ToString();
  402. r["Sort"] = row["Sort"].ToString();
  403. r["Location"] = row["Location"].ToString();
  404. r["Qty"] = row["Qty"].ToString();
  405. r["Finished Weight(ct)"] = string.IsNullOrEmpty(row["FinishedWeight"].ToString()) ? "0" : row["FinishedWeight"].ToString();
  406. r["Rough Weight(ct)"] = string.IsNullOrEmpty(row["RoughWeight"].ToString()) ? "0" : row["RoughWeight"].ToString();
  407. r["Price(USD)"] = string.IsNullOrEmpty(row["Price"].ToString()) ? 0 : decimal.Parse(row["Price"].ToString());
  408. r["Shape"] = row["Shape"].ToString();
  409. r["CertificateNo"] = row["CertificateNo"].ToString();
  410. r["Color"] = row["Color"].ToString();
  411. r["Clarity"] = row["Clarity"].ToString();
  412. r["Polish"] = row["Polish"].ToString();
  413. dtExport.Rows.Add(r);
  414. number++;
  415. }
  416. gv.DataSource = dtExport;
  417. gv.DataBind();
  418. Export2(gv);
  419. }
  420. }
  421. /// <summary>
  422. /// Replace any of the contained controls with literals
  423. /// </summary>
  424. /// <param name="control"></param>
  425. private static void PrepareControlForExport(Control control)
  426. {
  427. for (int i = 0; i < control.Controls.Count; i++)
  428. {
  429. Control current = control.Controls[i];
  430. if (current is LinkButton)
  431. {
  432. control.Controls.Remove(current);
  433. control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
  434. }
  435. else if (current is ImageButton)
  436. {
  437. control.Controls.Remove(current);
  438. control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
  439. }
  440. else if (current is HyperLink)
  441. {
  442. control.Controls.Remove(current);
  443. control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
  444. }
  445. else if (current is DropDownList)
  446. {
  447. control.Controls.Remove(current);
  448. control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
  449. }
  450. else if (current is CheckBox)
  451. {
  452. control.Controls.Remove(current);
  453. control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
  454. }
  455. if (current.HasControls())
  456. {
  457. GridViewExportUtil.PrepareControlForExport(current);
  458. }
  459. }
  460. }
  461. }
  462. public class AsposeCell
  463. {
  464. //public static void Export(DataTable dt)
  465. //{
  466. // var name = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random(DateTime.Now.Second).Next(10000) + ".xls";
  467. // MemoryStream ms = OutFileToStream(dt);
  468. // HttpContext.Current.Response.Clear();
  469. // HttpContext.Current.Response.ContentType = "application/ms-excel";
  470. // HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
  471. // HttpContext.Current.Response.Charset = "utf-8";
  472. // HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
  473. // HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());
  474. // HttpContext.Current.Response.BinaryWrite(ms.ToArray());
  475. // HttpContext.Current.Response.Flush();
  476. // HttpContext.Current.Response.Clear();
  477. // HttpContext.Current.Response.End();
  478. //}
  479. public static void Export(DataTable dt)
  480. {
  481. var name = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random(DateTime.Now.Second).Next(10000) + ".xlsx";
  482. MemoryStream ms = OutFileToStream(dt);
  483. HttpContext.Current.Response.Clear();
  484. HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // Set content type to xlsx
  485. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
  486. HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());
  487. HttpContext.Current.Response.BinaryWrite(ms.ToArray());
  488. HttpContext.Current.Response.Flush();
  489. HttpContext.Current.Response.Clear();
  490. HttpContext.Current.Response.End();
  491. }
  492. public static void ExportbackColor(DataTable dt)
  493. {
  494. var name = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random(DateTime.Now.Second).Next(10000) + ".xls";
  495. MemoryStream ms = OutFileToStreamBackColor(dt);
  496. HttpContext.Current.Response.Clear();
  497. HttpContext.Current.Response.ContentType = "application/ms-excel";
  498. HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
  499. HttpContext.Current.Response.Charset = "utf-8";
  500. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
  501. HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());
  502. HttpContext.Current.Response.BinaryWrite(ms.ToArray());
  503. HttpContext.Current.Response.Flush();
  504. HttpContext.Current.Response.Clear();
  505. HttpContext.Current.Response.End();
  506. }
  507. public static void Export(DataTable dt, string xlsName)
  508. {
  509. var name = xlsName + DateTime.Now.ToString("yyyyMMddHHmmss") + new Random(DateTime.Now.Second).Next(10000) + ".xls";
  510. MemoryStream ms = OutFileToStream(dt);
  511. HttpContext.Current.Response.Clear();
  512. HttpContext.Current.Response.ContentType = "application/ms-excel";
  513. HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
  514. HttpContext.Current.Response.Charset = "utf-8";
  515. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
  516. HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());
  517. HttpContext.Current.Response.BinaryWrite(ms.ToArray());
  518. HttpContext.Current.Response.Flush();
  519. HttpContext.Current.Response.Clear();
  520. HttpContext.Current.Response.End();
  521. }
  522. public static void Export(MemoryStream ms)
  523. {
  524. var name = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random(DateTime.Now.Second).Next(10000) + ".xls";
  525. HttpContext.Current.Response.Clear();
  526. HttpContext.Current.Response.ContentType = "application/ms-excel";
  527. HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
  528. HttpContext.Current.Response.Charset = "utf-8";
  529. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
  530. HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());
  531. HttpContext.Current.Response.BinaryWrite(ms.ToArray());
  532. HttpContext.Current.Response.Flush();
  533. HttpContext.Current.Response.Clear();
  534. HttpContext.Current.Response.End();
  535. }
  536. public static void Export(MemoryStream ms, string name)
  537. {
  538. HttpContext.Current.Response.Clear();
  539. HttpContext.Current.Response.ContentType = "application/ms-excel";
  540. if (name.ToLower().Contains(".xlsm"))
  541. {
  542. HttpContext.Current.Response.ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
  543. }
  544. HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
  545. HttpContext.Current.Response.Charset = "utf-8";
  546. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
  547. HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());
  548. HttpContext.Current.Response.BinaryWrite(ms.ToArray());
  549. HttpContext.Current.Response.Flush();
  550. HttpContext.Current.Response.Clear();
  551. HttpContext.Current.Response.End();
  552. }
  553. //xls
  554. //public static MemoryStream OutFileToStream(DataTable dt)
  555. //{
  556. // Workbook workbook = new Workbook(); //工作簿
  557. // workbook.Worksheets.Clear();
  558. // for (int j = 0; j < System.Math.Ceiling((dt.Rows.Count / (double)65534)); j++)
  559. // {
  560. // workbook.Worksheets.Add("" + j);
  561. // Worksheet sheet = workbook.Worksheets[j];
  562. // Cells cells = sheet.Cells;//单元格
  563. // //为标题设置样式
  564. // Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式
  565. // styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  566. // styleTitle.Font.Name = "宋体";//文字字体
  567. // styleTitle.Font.Size = 18;//文字大小
  568. // styleTitle.Font.IsBold = true;//粗体
  569. // //样式2
  570. // Aspose.Cells.Style style2 = workbook.Styles[workbook.Styles.Add()];//新增样式
  571. // style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  572. // style2.Font.Name = "宋体";//文字字体
  573. // style2.Font.Size = 14;//文字大小
  574. // style2.Font.IsBold = true;//粗体
  575. // style2.IsTextWrapped = false;//单元格内容自动换行
  576. // //样式3
  577. // Aspose.Cells.Style style3 = workbook.Styles[workbook.Styles.Add()];//新增样式
  578. // style3.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  579. // style3.Font.Name = "宋体";//文字字体
  580. // style3.Font.Size = 12;//文字大小
  581. // style3.IsTextWrapped = false;//单元格内容自动换行
  582. // int Colnum = dt.Columns.Count;//表格列数
  583. // int Rownum = dt.Rows.Count;//表格行数
  584. // //生成行2 列名行
  585. // for (int i = 0; i < Colnum; i++)
  586. // {
  587. // cells[0, i].PutValue(dt.Columns[i].ColumnName);
  588. // cells[0, i].SetStyle(style2);
  589. // cells.SetRowHeight(0, 25);
  590. // //for (int col = 0; col < Colnum; col++)
  591. // //{
  592. // // sheet.AutoFitColumn(col, 0, Rownum-1);
  593. // //}
  594. // for (int col = 0; col < Colnum; col++)
  595. // {
  596. // cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 10);
  597. // }
  598. // }
  599. // //生成数据行
  600. // for (int i = 0; i < 65534; i++)
  601. // {
  602. // if ((j * 65534 + i) >= Rownum)
  603. // {
  604. // break;
  605. // }
  606. // for (int k = 0; k < Colnum; k++)
  607. // {
  608. // cells[1 + i, k].PutValue(dt.Rows[j * 65534 + i][k].ToString());
  609. // cells[1 + i, k].SetStyle(style3);
  610. // }
  611. // cells.SetRowHeight(1 + i, 24);
  612. // }
  613. // }
  614. // MemoryStream ms = workbook.SaveToStream();
  615. // return ms;
  616. //}
  617. //public static MemoryStream1 OutFileToStream(DataTable dt)
  618. //{
  619. // Workbook workbook = new Workbook();
  620. // workbook.Worksheets.Clear();
  621. // workbook.Worksheets.Add("" + 0);
  622. // Worksheet sheet = workbook.Worksheets[0]; // 只使用一个工作表
  623. // Cells cells = sheet.Cells; // 单元格
  624. // // 为标题设置样式
  625. // Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];
  626. // styleTitle.HorizontalAlignment = TextAlignmentType.Center; // 文字居中
  627. // styleTitle.Font.Name = "宋体"; // 文字字体
  628. // styleTitle.Font.Size = 18; // 文字大小
  629. // styleTitle.Font.IsBold = true; // 粗体
  630. // // 样式2
  631. // Aspose.Cells.Style style2 = workbook.Styles[workbook.Styles.Add()];
  632. // style2.HorizontalAlignment = TextAlignmentType.Center; // 文字居中
  633. // style2.Font.Name = "宋体"; // 文字字体
  634. // style2.Font.Size = 14; // 文字大小
  635. // style2.Font.IsBold = true; // 粗体
  636. // // 样式3
  637. // Aspose.Cells.Style style3 = workbook.Styles[workbook.Styles.Add()];
  638. // style3.HorizontalAlignment = TextAlignmentType.Center; // 文字居中
  639. // style3.Font.Name = "宋体"; // 文字字体
  640. // style3.Font.Size = 12; // 文字大小
  641. // int Colnum = dt.Columns.Count; // 表格列数
  642. // int Rownum = dt.Rows.Count; // 表格行数
  643. // // 生成列名行
  644. // for (int i = 0; i < Colnum; i++)
  645. // {
  646. // cells[0, i].PutValue(dt.Columns[i].ColumnName);
  647. // cells[0, i].SetStyle(style2);
  648. // cells.SetRowHeight(0, 25);
  649. // cells.SetColumnWidthPixel(i, cells.GetColumnWidthPixel(i) + 10);
  650. // }
  651. // // 生成数据行
  652. // for (int i = 0; i < Rownum; i++)
  653. // {
  654. // for (int k = 0; k < Colnum; k++)
  655. // {
  656. // cells[1 + i, k].PutValue(dt.Rows[i][k].ToString());
  657. // cells[1 + i, k].SetStyle(style3);
  658. // cells.SetRowHeight(1 + i, 24);
  659. // }
  660. // }
  661. // MemoryStream ms = new MemoryStream();
  662. // workbook.Save(ms, SaveFormat.Xlsx); // 修改为保存为 .xlsx 格式
  663. // ms.Position = 0; // 复位 MemoryStream 的位置
  664. // return ms;
  665. //}
  666. //xlsx
  667. public static MemoryStream OutFileToStream(DataTable dt)
  668. {
  669. Workbook workbook = new Workbook(); //工作簿
  670. workbook.Worksheets.Clear();
  671. workbook.Worksheets.Add("Sheet1"); // 添加一个工作表
  672. Worksheet sheet = workbook.Worksheets[0];
  673. Cells cells = sheet.Cells; // 单元格
  674. // 为标题设置样式
  675. Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];
  676. styleTitle.HorizontalAlignment = TextAlignmentType.Center; // 文字居中
  677. styleTitle.Font.Name = "宋体"; // 文字字体
  678. styleTitle.Font.Size = 18; // 文字大小
  679. styleTitle.Font.IsBold = true; // 粗体
  680. // 样式2 - 列名样式
  681. Aspose.Cells.Style style2 = workbook.Styles[workbook.Styles.Add()];
  682. style2.HorizontalAlignment = TextAlignmentType.Center; // 文字居中
  683. style2.Font.Name = "宋体"; // 文字字体
  684. style2.Font.Size = 14; // 文字大小
  685. style2.Font.IsBold = true; // 粗体
  686. style2.IsTextWrapped = false; // 单元格内容自动换行
  687. // 样式3 - 数据样式
  688. Aspose.Cells.Style style3 = workbook.Styles[workbook.Styles.Add()];
  689. style3.HorizontalAlignment = TextAlignmentType.Center; // 文字居中
  690. style3.Font.Name = "宋体"; // 文字字体
  691. style3.Font.Size = 12; // 文字大小
  692. style3.IsTextWrapped = false; // 单元格内容自动换行
  693. int Colnum = dt.Columns.Count; // 表格列数
  694. int Rownum = dt.Rows.Count; // 表格行数
  695. // 生成列名行
  696. for (int i = 0; i < Colnum; i++)
  697. {
  698. cells[0, i].PutValue(dt.Columns[i].ColumnName);
  699. cells[0, i].SetStyle(style2);
  700. cells.SetRowHeight(0, 25);
  701. }
  702. // 调整列宽
  703. for (int col = 0; col < Colnum; col++)
  704. {
  705. cells.SetColumnWidthPixel(col, 120); // 设置固定列宽,避免循环调整
  706. }
  707. // 生成数据行
  708. for (int i = 0; i < Rownum; i++)
  709. {
  710. for (int k = 0; k < Colnum; k++)
  711. {
  712. string columnName = dt.Columns[k].ColumnName;
  713. object cellValue = dt.Rows[i][k];
  714. // 检查列名是否包含"数量"字段
  715. if (columnName.Contains("数量"))
  716. {
  717. // 尝试将值转换为数值类型
  718. if (cellValue != null && cellValue != DBNull.Value)
  719. {
  720. // 尝试转换为数值类型
  721. double numericValue;
  722. if (double.TryParse(cellValue.ToString(), out numericValue))
  723. {
  724. // 设置为数值类型并保留两位小数
  725. cells[1 + i, k].PutValue(numericValue);
  726. // 创建数值样式
  727. Aspose.Cells.Style numericStyle = workbook.Styles[workbook.Styles.Add()];
  728. numericStyle.Copy(style3);
  729. numericStyle.Number = 2; // 0.00格式
  730. cells[1 + i, k].SetStyle(numericStyle);
  731. }
  732. else
  733. {
  734. // 转换失败,按原字符串处理
  735. cells[1 + i, k].PutValue(cellValue.ToString());
  736. cells[1 + i, k].SetStyle(style3);
  737. }
  738. }
  739. else
  740. {
  741. // 值为空,设置为空字符串
  742. cells[1 + i, k].PutValue("");
  743. cells[1 + i, k].SetStyle(style3);
  744. }
  745. }
  746. // 检查列名是否包含"日期"字段
  747. else if (columnName.Contains("日期"))
  748. {
  749. // 尝试将值转换为日期类型
  750. if (cellValue != null && cellValue != DBNull.Value)
  751. {
  752. DateTime dateValue;
  753. // 尝试转换为日期类型
  754. if (DateTime.TryParse(cellValue.ToString(), out dateValue))
  755. {
  756. // 设置为日期类型
  757. cells[1 + i, k].PutValue(dateValue);
  758. // 创建日期样式
  759. Aspose.Cells.Style dateStyle = workbook.Styles[workbook.Styles.Add()];
  760. dateStyle.Copy(style3);
  761. dateStyle.Number = 14; // 短日期格式 (yyyy-mm-dd)
  762. cells[1 + i, k].SetStyle(dateStyle);
  763. }
  764. else
  765. {
  766. // 转换失败,按原字符串处理
  767. cells[1 + i, k].PutValue(cellValue.ToString());
  768. cells[1 + i, k].SetStyle(style3);
  769. }
  770. }
  771. else
  772. {
  773. // 值为空,设置为空字符串
  774. cells[1 + i, k].PutValue("");
  775. cells[1 + i, k].SetStyle(style3);
  776. }
  777. }
  778. else
  779. {
  780. // 普通文本处理
  781. cells[1 + i, k].PutValue(cellValue?.ToString() ?? "");
  782. cells[1 + i, k].SetStyle(style3);
  783. }
  784. }
  785. cells.SetRowHeight(1 + i, 24);
  786. }
  787. // 添加自动筛选功能
  788. if (Rownum > 0)
  789. {
  790. // 创建自动筛选,范围从第1行(0索引)到最后一行,涵盖所有列
  791. sheet.AutoFilter.Range = $"A1:{GetExcelColumnName(Colnum - 1)}{Rownum + 1}";
  792. }
  793. // 保存为 .xlsx 格式
  794. MemoryStream ms = new MemoryStream();
  795. workbook.Save(ms, SaveFormat.Xlsx);
  796. ms.Position = 0; // 复位 MemoryStream 的位置
  797. return ms;
  798. }
  799. // 获取Excel列名,例如0返回A,25返回Z,26返回AA等
  800. private static string GetExcelColumnName(int columnIndex)
  801. {
  802. string columnName = "";
  803. while (columnIndex >= 0)
  804. {
  805. columnName = (char)('A' + columnIndex % 26) + columnName;
  806. columnIndex = columnIndex / 26 - 1;
  807. }
  808. return columnName;
  809. }
  810. public static MemoryStream OutFileToStreamBackColor(DataTable dt)
  811. {
  812. Workbook workbook = new Workbook(); //工作簿
  813. workbook.Worksheets.Clear();
  814. for (int j = 0; j < System.Math.Ceiling((dt.Rows.Count / (double)65534)); j++)
  815. {
  816. workbook.Worksheets.Add("" + j);
  817. Worksheet sheet = workbook.Worksheets[j];
  818. Cells cells = sheet.Cells;//单元格
  819. //为标题设置样式
  820. Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式
  821. styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  822. styleTitle.Font.Name = "宋体";//文字字体
  823. styleTitle.Font.Size = 18;//文字大小
  824. styleTitle.Font.IsBold = true;//粗体
  825. styleTitle.ForegroundColor = System.Drawing.Color.Silver;
  826. //样式2
  827. Aspose.Cells.Style style2 = workbook.Styles[workbook.Styles.Add()];//新增样式
  828. style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  829. style2.Font.Name = "宋体";//文字字体
  830. style2.Font.Size = 14;//文字大小
  831. style2.Font.IsBold = true;//粗体
  832. style2.IsTextWrapped = false;//单元格内容自动换行
  833. style2.ForegroundColor = Color.Red;//设置背景颜色
  834. style2.Pattern = BackgroundType.Solid;//开启背景颜色
  835. //样式4
  836. Aspose.Cells.Style style4 = workbook.Styles[workbook.Styles.Add()];//新增样式
  837. style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  838. style2.Font.Name = "宋体";//文字字体
  839. style2.Font.Size = 14;//文字大小
  840. style2.Font.IsBold = true;//粗体
  841. style2.IsTextWrapped = false;//单元格内容自动换行
  842. //样式3
  843. Aspose.Cells.Style style3 = workbook.Styles[workbook.Styles.Add()];//新增样式
  844. style3.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  845. style3.Font.Name = "宋体";//文字字体
  846. style3.Font.Size = 12;//文字大小
  847. style3.IsTextWrapped = false;//单元格内容自动换行
  848. style3.ForegroundColor = System.Drawing.Color.Silver;
  849. int Colnum = dt.Columns.Count;//表格列数
  850. int Rownum = dt.Rows.Count;//表格行数
  851. //生成行2 列名行
  852. for (int i = 0; i < Colnum; i++)
  853. {
  854. cells[0, i].PutValue(dt.Columns[i].ColumnName);
  855. if(dt.Columns[i].ColumnName=="物料编码"|| dt.Columns[i].ColumnName == "仓库"|| dt.Columns[i].ColumnName == "库位" || dt.Columns[i].ColumnName == "库位数量"|| dt.Columns[i].ColumnName == "最小包装数量" || dt.Columns[i].ColumnName == "生产日期")
  856. {
  857. cells[0, i].SetStyle(style2);
  858. }
  859. else
  860. {
  861. cells[0, i].SetStyle(style4);
  862. }
  863. cells.SetRowHeight(0, 25);
  864. //for (int col = 0; col < Colnum; col++)
  865. //{
  866. // sheet.AutoFitColumn(col, 0, Rownum-1);
  867. //}
  868. for (int col = 0; col < Colnum; col++)
  869. {
  870. cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 10);
  871. }
  872. }
  873. //生成数据行
  874. for (int i = 0; i < 65534; i++)
  875. {
  876. if ((j * 65534 + i) >= Rownum)
  877. {
  878. break;
  879. }
  880. for (int k = 0; k < Colnum; k++)
  881. {
  882. cells[1 + i, k].PutValue(dt.Rows[j * 65534 + i][k].ToString());
  883. cells[1 + i, k].SetStyle(style3);
  884. }
  885. cells.SetRowHeight(1 + i, 24);
  886. }
  887. }
  888. MemoryStream ms = workbook.SaveToStream();
  889. return ms;
  890. }
  891. public static MemoryStream OutFileToStream(DataSet ds, List<String> SheetNameList)
  892. {
  893. Workbook workbook = new Workbook(); //工作簿
  894. workbook.Worksheets.Clear();
  895. int sheetIndex = 0;
  896. for (int jj = 0; jj < ds.Tables.Count; jj++)
  897. {
  898. DataTable dt = ds.Tables[jj];
  899. for (int j = 0; j < System.Math.Ceiling((dt.Rows.Count / (double)65534)); j++)
  900. {
  901. workbook.Worksheets.Add(sheetIndex + SheetNameList[jj]);
  902. Worksheet sheet = workbook.Worksheets[sheetIndex];
  903. sheetIndex++;
  904. Cells cells = sheet.Cells;//单元格
  905. //为标题设置样式
  906. Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式
  907. styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  908. styleTitle.Font.Name = "宋体";//文字字体
  909. styleTitle.Font.Size = 18;//文字大小
  910. styleTitle.Font.IsBold = true;//粗体
  911. //样式2
  912. Aspose.Cells.Style style2 = workbook.Styles[workbook.Styles.Add()];//新增样式
  913. style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  914. style2.Font.Name = "宋体";//文字字体
  915. style2.Font.Size = 14;//文字大小
  916. style2.Font.IsBold = true;//粗体
  917. style2.IsTextWrapped = false;//单元格内容自动换行
  918. //样式3
  919. Aspose.Cells.Style style3 = workbook.Styles[workbook.Styles.Add()];//新增样式
  920. style3.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  921. style3.Font.Name = "宋体";//文字字体
  922. style3.Font.Size = 12;//文字大小
  923. style2.IsTextWrapped = false;//单元格内容自动换行
  924. int Colnum = dt.Columns.Count;//表格列数
  925. int Rownum = dt.Rows.Count;//表格行数
  926. //生成行2 列名行
  927. for (int i = 0; i < Colnum; i++)
  928. {
  929. cells[0, i].PutValue(dt.Columns[i].ColumnName);
  930. cells[0, i].SetStyle(style2);
  931. cells.SetRowHeight(0, 25);
  932. //for (int col = 0; col < Colnum; col++)
  933. //{
  934. // sheet.AutoFitColumn(col, 0, Rownum-1);
  935. //}
  936. for (int col = 0; col < Colnum; col++)
  937. {
  938. cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 10);
  939. }
  940. }
  941. //生成数据行
  942. for (int i = 0; i < 65534; i++)
  943. {
  944. if ((j * 65534 + i) >= Rownum)
  945. {
  946. break;
  947. }
  948. for (int k = 0; k < Colnum; k++)
  949. {
  950. cells[1 + i, k].PutValue(dt.Rows[j * 65534 + i][k].ToString());
  951. cells[1 + i, k].SetStyle(style3);
  952. }
  953. cells.SetRowHeight(1 + i, 24);
  954. }
  955. }
  956. }
  957. MemoryStream ms = workbook.SaveToStream();
  958. return ms;
  959. }
  960. }
  961. public class FileToExcel
  962. {
  963. /// <summary>
  964. /// Excel导入成Datable
  965. /// </summary>
  966. /// <param name="file">导入路径(包含文件名与扩展名)</param>
  967. /// <returns></returns>
  968. public static DataTable ExcelToTable(string file)
  969. {
  970. DataTable dt = new DataTable();
  971. IWorkbook workbook;
  972. try
  973. {
  974. string fileExt = Path.GetExtension(file).ToLower();
  975. using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
  976. {
  977. //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
  978. if (fileExt == ".xlsx")
  979. { workbook = new XSSFWorkbook(fs); }
  980. else if (fileExt == ".xls")
  981. { workbook = new HSSFWorkbook(fs); }
  982. else { workbook = null; }
  983. if (workbook == null) { return null; }
  984. ISheet sheet = workbook.GetSheetAt(0);
  985. //表头
  986. IRow header = sheet.GetRow(sheet.FirstRowNum);
  987. List<int> columns = new List<int>();
  988. for (int i = 0; i < header.LastCellNum; i++)
  989. {
  990. ICell cell = header.GetCell(i);
  991. var FillForegroundColor = cell.CellStyle.FillForegroundColor.ToString();
  992. object obj = GetValueType(cell);
  993. if (obj == null || obj.ToString() == string.Empty)
  994. {
  995. //dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
  996. }
  997. else
  998. {
  999. DataColumn dc = new DataColumn(obj.ToString());
  1000. if (FillForegroundColor == "15")
  1001. dc.AllowDBNull = false;
  1002. else
  1003. dc.AllowDBNull = true;
  1004. dt.Columns.Add(dc);
  1005. columns.Add(i);
  1006. }
  1007. }
  1008. //判断模板栏位是否正确 略
  1009. #region 判断模板是否正确
  1010. #endregion
  1011. //end 判断模板栏位正确
  1012. //数据
  1013. for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
  1014. {
  1015. DataRow dr = dt.NewRow();
  1016. bool hasValue = false;
  1017. foreach (int j in columns)
  1018. {
  1019. dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
  1020. if (!string.IsNullOrWhiteSpace(dr[j].ToString()))
  1021. {
  1022. hasValue = true;
  1023. }
  1024. else if (!dt.Columns[j].AllowDBNull)
  1025. {
  1026. string msg = "第 " + i + " 行,列" + dt.Columns[j].ColumnName + "没有输入值";
  1027. throw new Exception(msg);
  1028. }
  1029. }
  1030. if (hasValue)
  1031. {
  1032. dt.Rows.Add(dr);
  1033. }
  1034. }
  1035. }
  1036. return dt;
  1037. }
  1038. catch (Exception ex)
  1039. {
  1040. throw ex;
  1041. }
  1042. }
  1043. /// <summary>
  1044. /// 获取单元格类型
  1045. /// </summary>
  1046. /// <param name="cell"></param>
  1047. /// <returns></returns>
  1048. public static object GetValueType(ICell cell)
  1049. {
  1050. if (cell == null)
  1051. return null;
  1052. switch (cell.CellType)
  1053. {
  1054. case CellType.Blank: //BLANK:
  1055. return null;
  1056. case CellType.Boolean: //BOOLEAN:
  1057. return cell.BooleanCellValue;
  1058. case CellType.Numeric:
  1059. //NUMERIC:
  1060. //{
  1061. // var time= cell.DateCellValue;
  1062. // if (1==1)
  1063. // return cell.NumericCellValue;
  1064. //}
  1065. if (HSSFDateUtil.IsCellDateFormatted(cell))
  1066. {
  1067. return cell.DateCellValue;
  1068. }
  1069. else
  1070. {
  1071. return cell.NumericCellValue;
  1072. }
  1073. case CellType.String: //STRING:
  1074. return cell.StringCellValue;
  1075. case CellType.Error: //ERROR:
  1076. return cell.ErrorCellValue;
  1077. case CellType.Formula: //FORMULA:
  1078. default:
  1079. return "=" + cell.CellFormula;
  1080. }
  1081. return cell.StringCellValue;
  1082. }
  1083. }
  1084. }