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.

1008 lines
44 KiB

8 months 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 ExportbackColor(DataTable dt)
  480. {
  481. var name = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random(DateTime.Now.Second).Next(10000) + ".xls";
  482. MemoryStream ms = OutFileToStreamBackColor(dt);
  483. HttpContext.Current.Response.Clear();
  484. HttpContext.Current.Response.ContentType = "application/ms-excel";
  485. HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
  486. HttpContext.Current.Response.Charset = "utf-8";
  487. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
  488. HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());
  489. HttpContext.Current.Response.BinaryWrite(ms.ToArray());
  490. HttpContext.Current.Response.Flush();
  491. HttpContext.Current.Response.Clear();
  492. HttpContext.Current.Response.End();
  493. }
  494. public static void Export(DataTable dt, string xlsName)
  495. {
  496. var name = xlsName + DateTime.Now.ToString("yyyyMMddHHmmss") + new Random(DateTime.Now.Second).Next(10000) + ".xls";
  497. MemoryStream ms = OutFileToStream(dt);
  498. HttpContext.Current.Response.Clear();
  499. HttpContext.Current.Response.ContentType = "application/ms-excel";
  500. HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
  501. HttpContext.Current.Response.Charset = "utf-8";
  502. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
  503. HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());
  504. HttpContext.Current.Response.BinaryWrite(ms.ToArray());
  505. HttpContext.Current.Response.Flush();
  506. HttpContext.Current.Response.Clear();
  507. HttpContext.Current.Response.End();
  508. }
  509. public static void Export(MemoryStream ms)
  510. {
  511. var name = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random(DateTime.Now.Second).Next(10000) + ".xls";
  512. HttpContext.Current.Response.Clear();
  513. HttpContext.Current.Response.ContentType = "application/ms-excel";
  514. HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
  515. HttpContext.Current.Response.Charset = "utf-8";
  516. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
  517. HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());
  518. HttpContext.Current.Response.BinaryWrite(ms.ToArray());
  519. HttpContext.Current.Response.Flush();
  520. HttpContext.Current.Response.Clear();
  521. HttpContext.Current.Response.End();
  522. }
  523. public static void Export(MemoryStream ms, string name)
  524. {
  525. HttpContext.Current.Response.Clear();
  526. HttpContext.Current.Response.ContentType = "application/ms-excel";
  527. if (name.ToLower().Contains(".xlsm"))
  528. {
  529. HttpContext.Current.Response.ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
  530. }
  531. HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
  532. HttpContext.Current.Response.Charset = "utf-8";
  533. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
  534. HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());
  535. HttpContext.Current.Response.BinaryWrite(ms.ToArray());
  536. HttpContext.Current.Response.Flush();
  537. HttpContext.Current.Response.Clear();
  538. HttpContext.Current.Response.End();
  539. }
  540. public static MemoryStream OutFileToStream(DataTable dt)
  541. {
  542. Workbook workbook = new Workbook(); //工作簿
  543. workbook.Worksheets.Clear();
  544. for (int j = 0; j < System.Math.Ceiling((dt.Rows.Count / (double)65534)); j++)
  545. {
  546. workbook.Worksheets.Add("" + j);
  547. Worksheet sheet = workbook.Worksheets[j];
  548. Cells cells = sheet.Cells;//单元格
  549. //为标题设置样式
  550. Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式
  551. styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  552. styleTitle.Font.Name = "宋体";//文字字体
  553. styleTitle.Font.Size = 18;//文字大小
  554. styleTitle.Font.IsBold = true;//粗体
  555. //样式2
  556. Aspose.Cells.Style style2 = workbook.Styles[workbook.Styles.Add()];//新增样式
  557. style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  558. style2.Font.Name = "宋体";//文字字体
  559. style2.Font.Size = 14;//文字大小
  560. style2.Font.IsBold = true;//粗体
  561. style2.IsTextWrapped = false;//单元格内容自动换行
  562. //样式3
  563. Aspose.Cells.Style style3 = workbook.Styles[workbook.Styles.Add()];//新增样式
  564. style3.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  565. style3.Font.Name = "宋体";//文字字体
  566. style3.Font.Size = 12;//文字大小
  567. style3.IsTextWrapped = false;//单元格内容自动换行
  568. int Colnum = dt.Columns.Count;//表格列数
  569. int Rownum = dt.Rows.Count;//表格行数
  570. //生成行2 列名行
  571. for (int i = 0; i < Colnum; i++)
  572. {
  573. cells[0, i].PutValue(dt.Columns[i].ColumnName);
  574. cells[0, i].SetStyle(style2);
  575. cells.SetRowHeight(0, 25);
  576. //for (int col = 0; col < Colnum; col++)
  577. //{
  578. // sheet.AutoFitColumn(col, 0, Rownum-1);
  579. //}
  580. for (int col = 0; col < Colnum; col++)
  581. {
  582. cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 10);
  583. }
  584. }
  585. //生成数据行
  586. for (int i = 0; i < 65534; i++)
  587. {
  588. if ((j * 65534 + i) >= Rownum)
  589. {
  590. break;
  591. }
  592. for (int k = 0; k < Colnum; k++)
  593. {
  594. cells[1 + i, k].PutValue(dt.Rows[j * 65534 + i][k].ToString());
  595. cells[1 + i, k].SetStyle(style3);
  596. }
  597. cells.SetRowHeight(1 + i, 24);
  598. }
  599. }
  600. MemoryStream ms = workbook.SaveToStream();
  601. return ms;
  602. }
  603. public static MemoryStream OutFileToStreamBackColor(DataTable dt)
  604. {
  605. Workbook workbook = new Workbook(); //工作簿
  606. workbook.Worksheets.Clear();
  607. for (int j = 0; j < System.Math.Ceiling((dt.Rows.Count / (double)65534)); j++)
  608. {
  609. workbook.Worksheets.Add("" + j);
  610. Worksheet sheet = workbook.Worksheets[j];
  611. Cells cells = sheet.Cells;//单元格
  612. //为标题设置样式
  613. Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式
  614. styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  615. styleTitle.Font.Name = "宋体";//文字字体
  616. styleTitle.Font.Size = 18;//文字大小
  617. styleTitle.Font.IsBold = true;//粗体
  618. styleTitle.ForegroundColor = System.Drawing.Color.Silver;
  619. //样式2
  620. Aspose.Cells.Style style2 = workbook.Styles[workbook.Styles.Add()];//新增样式
  621. style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  622. style2.Font.Name = "宋体";//文字字体
  623. style2.Font.Size = 14;//文字大小
  624. style2.Font.IsBold = true;//粗体
  625. style2.IsTextWrapped = false;//单元格内容自动换行
  626. style2.ForegroundColor = Color.Red;//设置背景颜色
  627. style2.Pattern = BackgroundType.Solid;//开启背景颜色
  628. //样式4
  629. Aspose.Cells.Style style4 = workbook.Styles[workbook.Styles.Add()];//新增样式
  630. style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  631. style2.Font.Name = "宋体";//文字字体
  632. style2.Font.Size = 14;//文字大小
  633. style2.Font.IsBold = true;//粗体
  634. style2.IsTextWrapped = false;//单元格内容自动换行
  635. //样式3
  636. Aspose.Cells.Style style3 = workbook.Styles[workbook.Styles.Add()];//新增样式
  637. style3.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  638. style3.Font.Name = "宋体";//文字字体
  639. style3.Font.Size = 12;//文字大小
  640. style3.IsTextWrapped = false;//单元格内容自动换行
  641. style3.ForegroundColor = System.Drawing.Color.Silver;
  642. int Colnum = dt.Columns.Count;//表格列数
  643. int Rownum = dt.Rows.Count;//表格行数
  644. //生成行2 列名行
  645. for (int i = 0; i < Colnum; i++)
  646. {
  647. cells[0, i].PutValue(dt.Columns[i].ColumnName);
  648. if(dt.Columns[i].ColumnName=="物料编码"|| dt.Columns[i].ColumnName == "条码"|| dt.Columns[i].ColumnName == "库位" || dt.Columns[i].ColumnName == "数量" || dt.Columns[i].ColumnName == "生产日期")
  649. {
  650. cells[0, i].SetStyle(style2);
  651. }
  652. else
  653. {
  654. cells[0, i].SetStyle(style4);
  655. }
  656. cells.SetRowHeight(0, 25);
  657. //for (int col = 0; col < Colnum; col++)
  658. //{
  659. // sheet.AutoFitColumn(col, 0, Rownum-1);
  660. //}
  661. for (int col = 0; col < Colnum; col++)
  662. {
  663. cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 10);
  664. }
  665. }
  666. //生成数据行
  667. for (int i = 0; i < 65534; i++)
  668. {
  669. if ((j * 65534 + i) >= Rownum)
  670. {
  671. break;
  672. }
  673. for (int k = 0; k < Colnum; k++)
  674. {
  675. cells[1 + i, k].PutValue(dt.Rows[j * 65534 + i][k].ToString());
  676. cells[1 + i, k].SetStyle(style3);
  677. }
  678. cells.SetRowHeight(1 + i, 24);
  679. }
  680. }
  681. MemoryStream ms = workbook.SaveToStream();
  682. return ms;
  683. }
  684. public static MemoryStream OutFileToStream(DataSet ds, List<String> SheetNameList)
  685. {
  686. Workbook workbook = new Workbook(); //工作簿
  687. workbook.Worksheets.Clear();
  688. int sheetIndex = 0;
  689. for (int jj = 0; jj < ds.Tables.Count; jj++)
  690. {
  691. DataTable dt = ds.Tables[jj];
  692. for (int j = 0; j < System.Math.Ceiling((dt.Rows.Count / (double)65534)); j++)
  693. {
  694. workbook.Worksheets.Add(sheetIndex + SheetNameList[jj]);
  695. Worksheet sheet = workbook.Worksheets[sheetIndex];
  696. sheetIndex++;
  697. Cells cells = sheet.Cells;//单元格
  698. //为标题设置样式
  699. Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式
  700. styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  701. styleTitle.Font.Name = "宋体";//文字字体
  702. styleTitle.Font.Size = 18;//文字大小
  703. styleTitle.Font.IsBold = true;//粗体
  704. //样式2
  705. Aspose.Cells.Style style2 = workbook.Styles[workbook.Styles.Add()];//新增样式
  706. style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  707. style2.Font.Name = "宋体";//文字字体
  708. style2.Font.Size = 14;//文字大小
  709. style2.Font.IsBold = true;//粗体
  710. style2.IsTextWrapped = false;//单元格内容自动换行
  711. //样式3
  712. Aspose.Cells.Style style3 = workbook.Styles[workbook.Styles.Add()];//新增样式
  713. style3.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  714. style3.Font.Name = "宋体";//文字字体
  715. style3.Font.Size = 12;//文字大小
  716. style2.IsTextWrapped = false;//单元格内容自动换行
  717. int Colnum = dt.Columns.Count;//表格列数
  718. int Rownum = dt.Rows.Count;//表格行数
  719. //生成行2 列名行
  720. for (int i = 0; i < Colnum; i++)
  721. {
  722. cells[0, i].PutValue(dt.Columns[i].ColumnName);
  723. cells[0, i].SetStyle(style2);
  724. cells.SetRowHeight(0, 25);
  725. //for (int col = 0; col < Colnum; col++)
  726. //{
  727. // sheet.AutoFitColumn(col, 0, Rownum-1);
  728. //}
  729. for (int col = 0; col < Colnum; col++)
  730. {
  731. cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 10);
  732. }
  733. }
  734. //生成数据行
  735. for (int i = 0; i < 65534; i++)
  736. {
  737. if ((j * 65534 + i) >= Rownum)
  738. {
  739. break;
  740. }
  741. for (int k = 0; k < Colnum; k++)
  742. {
  743. cells[1 + i, k].PutValue(dt.Rows[j * 65534 + i][k].ToString());
  744. cells[1 + i, k].SetStyle(style3);
  745. }
  746. cells.SetRowHeight(1 + i, 24);
  747. }
  748. }
  749. }
  750. MemoryStream ms = workbook.SaveToStream();
  751. return ms;
  752. }
  753. }
  754. public class FileToExcel
  755. {
  756. /// <summary>
  757. /// Excel导入成Datable
  758. /// </summary>
  759. /// <param name="file">导入路径(包含文件名与扩展名)</param>
  760. /// <returns></returns>
  761. public static DataTable ExcelToTable(string file)
  762. {
  763. DataTable dt = new DataTable();
  764. IWorkbook workbook;
  765. try
  766. {
  767. string fileExt = Path.GetExtension(file).ToLower();
  768. using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
  769. {
  770. //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
  771. if (fileExt == ".xlsx")
  772. { workbook = new XSSFWorkbook(fs); }
  773. else if (fileExt == ".xls")
  774. { workbook = new HSSFWorkbook(fs); }
  775. else { workbook = null; }
  776. if (workbook == null) { return null; }
  777. ISheet sheet = workbook.GetSheetAt(0);
  778. //表头
  779. IRow header = sheet.GetRow(sheet.FirstRowNum);
  780. List<int> columns = new List<int>();
  781. for (int i = 0; i < header.LastCellNum; i++)
  782. {
  783. ICell cell = header.GetCell(i);
  784. var FillForegroundColor = cell.CellStyle.FillForegroundColor.ToString();
  785. object obj = GetValueType(cell);
  786. if (obj == null || obj.ToString() == string.Empty)
  787. {
  788. //dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
  789. }
  790. else
  791. {
  792. DataColumn dc = new DataColumn(obj.ToString());
  793. if (FillForegroundColor == "15")
  794. dc.AllowDBNull = false;
  795. else
  796. dc.AllowDBNull = true;
  797. dt.Columns.Add(dc);
  798. columns.Add(i);
  799. }
  800. }
  801. //判断模板栏位是否正确 略
  802. #region 判断模板是否正确
  803. #endregion
  804. //end 判断模板栏位正确
  805. //数据
  806. for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
  807. {
  808. DataRow dr = dt.NewRow();
  809. bool hasValue = false;
  810. foreach (int j in columns)
  811. {
  812. dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
  813. if (!string.IsNullOrWhiteSpace(dr[j].ToString()))
  814. {
  815. hasValue = true;
  816. }
  817. else if (!dt.Columns[j].AllowDBNull)
  818. {
  819. string msg = "第 " + i + " 行,列" + dt.Columns[j].ColumnName + "没有输入值";
  820. throw new Exception(msg);
  821. }
  822. }
  823. if (hasValue)
  824. {
  825. dt.Rows.Add(dr);
  826. }
  827. }
  828. }
  829. return dt;
  830. }
  831. catch (Exception ex)
  832. {
  833. throw ex;
  834. }
  835. }
  836. /// <summary>
  837. /// 获取单元格类型
  838. /// </summary>
  839. /// <param name="cell"></param>
  840. /// <returns></returns>
  841. public static object GetValueType(ICell cell)
  842. {
  843. if (cell == null)
  844. return null;
  845. switch (cell.CellType)
  846. {
  847. case CellType.Blank: //BLANK:
  848. return null;
  849. case CellType.Boolean: //BOOLEAN:
  850. return cell.BooleanCellValue;
  851. case CellType.Numeric:
  852. //NUMERIC:
  853. //{
  854. // var time= cell.DateCellValue;
  855. // if (1==1)
  856. // return cell.NumericCellValue;
  857. //}
  858. if (HSSFDateUtil.IsCellDateFormatted(cell))
  859. {
  860. return cell.DateCellValue;
  861. }
  862. else
  863. {
  864. return cell.NumericCellValue;
  865. }
  866. case CellType.String: //STRING:
  867. return cell.StringCellValue;
  868. case CellType.Error: //ERROR:
  869. return cell.ErrorCellValue;
  870. case CellType.Formula: //FORMULA:
  871. default:
  872. return "=" + cell.CellFormula;
  873. }
  874. return cell.StringCellValue;
  875. }
  876. }
  877. }