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.

744 lines
33 KiB

2 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. namespace NFine.Code
  19. {
  20. public class ExcelHelper
  21. {
  22. /// <summary>
  23. /// 导出数据到EXCEL文件
  24. /// </summary>
  25. /// <param name="page">页面</param>
  26. /// <param name="gvExcel">导出的GrivView</param>
  27. public static void ExportToExcel(System.Web.UI.Page page, GridView dgExcel, HttpResponse Response, string fileName)
  28. {
  29. try
  30. {
  31. fileName = fileName + ".xls";
  32. page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
  33. Response.Clear();
  34. Response.Buffer = true;
  35. Response.Charset = "utf-8";
  36. Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
  37. Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
  38. Response.ContentType = "application/ms-excel";
  39. dgExcel.Page.EnableViewState = false;
  40. System.IO.StringWriter tw = new System.IO.StringWriter();
  41. System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
  42. dgExcel.RenderControl(hw);
  43. // 输出DataGrid内容
  44. Response.Write(tw.ToString());
  45. Response.End();
  46. }
  47. catch (Exception ex)
  48. {
  49. throw ex;
  50. }
  51. }
  52. }
  53. /// <summary>
  54. /// 导出EXCEL
  55. /// </summary>
  56. public class GridViewExportUtil
  57. {
  58. /// <summary>
  59. /// 将GRIDVIEW导出excel
  60. /// </summary>
  61. /// <param name="fileName">excel文件名</param>
  62. /// <param name="gv">GridView ID</param>
  63. public static void Export(GridView gv, string PreSellNo)
  64. {
  65. //dataGridView1.Columns[0].HeaderText 循环列判断是否要设置为数字类型
  66. List<int> list = new List<int>();
  67. int k = 0; //序号
  68. int p = 0; //价格
  69. int a = 0; //数量
  70. int d = 0; //折扣
  71. for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
  72. {
  73. //if (gv.HeaderRow.Cells[i].Text.Contains("F_Id") || gv.HeaderRow.Cells[i].Text.Contains("Product_Id"))
  74. //{
  75. // list.Add(i);
  76. //}
  77. if (gv.HeaderRow.Cells[i].Text.Contains("No.") || gv.HeaderRow.Cells[i].Text.Contains("Finished Weight(ct)") ||
  78. gv.HeaderRow.Cells[i].Text.Contains("Rough Weight(ct)") || gv.HeaderRow.Cells[i].Text.Contains("Price(USD)") ||
  79. gv.HeaderRow.Cells[i].Text.Contains("Amount(USD)"))
  80. {
  81. list.Add(i);
  82. }
  83. //if (gv.HeaderRow.Cells[i].Text.Contains("No."))
  84. // k = i;
  85. if (gv.HeaderRow.Cells[i].Text.Contains("Price(USD)"))
  86. p = i;
  87. if (gv.HeaderRow.Cells[i].Text.Contains("Amount(USD)"))
  88. a = i;
  89. //if (gv.HeaderRow.Cells[i].Text.Contains("Discount(%)"))
  90. // d = i;
  91. }
  92. foreach (GridViewRow row in gv.Rows)
  93. {
  94. int j = 0;
  95. foreach (TableCell cell in row.Cells)
  96. {
  97. if (!list.Contains(j))
  98. {
  99. cell.Style.Add("vnd.ms-excel.numberformat", "@");//给表格内容设置样式
  100. } // end foreach (TableCell cell in row.Cells)
  101. else
  102. {
  103. if (j != 0)
  104. {
  105. if (j == p || j == a)
  106. cell.Style.Add("vnd.ms-excel.numberformat", "#,##0.00");
  107. //else if (j == d)
  108. // cell.Style.Add("vnd.ms-excel.numberformat", "#0%");
  109. else
  110. cell.Style.Add("vnd.ms-excel.numberformat", "#,##0.000");//保留三位小数的样式,否则为默认样式
  111. }
  112. }
  113. j++;
  114. }
  115. } // end foreach (GridViewRow row in dgExcel.Rows)
  116. HttpContext.Current.Response.Clear();
  117. string styleText = @"<style> .text{mso-number-format:\@;} </style> ";
  118. string fileName = "";
  119. if (!string.IsNullOrEmpty(PreSellNo))
  120. fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "-OrderNo[" + PreSellNo + "].xls";
  121. else
  122. fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
  123. HttpContext.Current.Response.AddHeader(
  124. "content-disposition", string.Format("attachment; filename={0}", fileName));
  125. HttpContext.Current.Response.ContentType = "application/ms-excel";
  126. HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
  127. using (StringWriter sw = new StringWriter())
  128. {
  129. using (HtmlTextWriter htw = new HtmlTextWriter(sw))
  130. {
  131. // Create a form to contain the grid
  132. Table table = new Table();
  133. table.GridLines = gv.GridLines;
  134. if (gv.HeaderRow != null)
  135. {
  136. GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
  137. table.Rows.Add(gv.HeaderRow);
  138. for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
  139. {
  140. table.Rows[0].Cells[i].BackColor = System.Drawing.Color.FromArgb(220, 240, 241);
  141. table.Rows[0].Cells[i].ForeColor = System.Drawing.Color.Black;
  142. table.Rows[0].Cells[i].Height = Unit.Pixel(24);
  143. }
  144. }
  145. // add each of the data rows to the table
  146. foreach (GridViewRow row in gv.Rows)
  147. {
  148. GridViewExportUtil.PrepareControlForExport(row);
  149. row.Height = Unit.Pixel(22);
  150. row.HorizontalAlign = HorizontalAlign.Center;
  151. table.Rows.Add(row);
  152. }
  153. // add the footer row to the table
  154. if (gv.FooterRow != null)
  155. {
  156. GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
  157. table.Rows.Add(gv.FooterRow);
  158. }
  159. #region 手动增加头部三行和底部一行
  160. #region ItemList表头行
  161. table.Rows.AddAt(0, new TableRow());
  162. table.Rows[0].Cells.Add(new TableCell());
  163. table.Rows[0].Cells[0].Text = "ITEMS LIST";
  164. table.Rows[0].Cells[0].Font.Bold = true;
  165. table.Rows[0].Cells[0].ColumnSpan = 9;
  166. table.Rows[0].Cells[0].BackColor = System.Drawing.Color.FromArgb(220, 240, 241);
  167. table.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Black;
  168. table.Rows[0].Cells[0].Height = Unit.Pixel(24);
  169. table.Rows[0].Cells[0].Font.Size = FontUnit.Parse("16");
  170. table.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
  171. table.Rows[0].Cells[0].BorderWidth = 0;
  172. table.Rows[0].BorderStyle = System.Web.UI.WebControls.BorderStyle.None;
  173. #endregion
  174. #region To S/C No 行
  175. table.Rows.AddAt(1, new TableRow());
  176. table.Rows[1].Cells.Add(new TableCell());
  177. table.Rows[1].Cells[0].Text = "TO:";
  178. table.Rows[1].Cells[0].Font.Bold = true;
  179. table.Rows[1].Cells[0].ColumnSpan = 4;
  180. table.Rows[1].Cells[0].HorizontalAlign = HorizontalAlign.Left;
  181. table.Rows[1].Cells[0].BorderWidth = 0;
  182. table.Rows[1].Cells.Add(new TableCell());
  183. table.Rows[1].Cells[1].Text = "";
  184. table.Rows[1].Cells[1].ColumnSpan = 2;
  185. table.Rows[1].Cells[1].BorderWidth = 0;
  186. table.Rows[1].Cells.Add(new TableCell());
  187. table.Rows[1].Cells[2].Text = "S/C NO:";
  188. table.Rows[1].Cells[2].Font.Bold = true;
  189. table.Rows[1].Cells[2].ColumnSpan = 3;
  190. table.Rows[1].Cells[2].HorizontalAlign = HorizontalAlign.Left;
  191. table.Rows[1].Cells[2].BorderWidth = 0;
  192. #endregion
  193. #region Date 行
  194. table.Rows.AddAt(2, new TableRow());
  195. table.Rows[2].Cells.Add(new TableCell());
  196. table.Rows[2].Cells[0].Text = "";
  197. table.Rows[2].Cells[0].ColumnSpan = 4;
  198. table.Rows[2].Cells[0].HorizontalAlign = HorizontalAlign.Left;
  199. table.Rows[2].Cells[0].BorderWidth = 0;
  200. table.Rows[2].Cells.Add(new TableCell());
  201. table.Rows[2].Cells[1].Text = "";
  202. table.Rows[2].Cells[1].ColumnSpan = 2;
  203. table.Rows[2].Cells[1].BorderWidth = 0;
  204. table.Rows[2].Cells.Add(new TableCell());
  205. table.Rows[2].Cells[2].Text = "DATE:" + DateTime.Now.ToString("yyyy-MM-dd");
  206. table.Rows[2].Cells[2].Font.Bold = true;
  207. table.Rows[2].Cells[2].ColumnSpan = 3;
  208. table.Rows[2].Cells[2].HorizontalAlign = HorizontalAlign.Left;
  209. table.Rows[2].Cells[2].BorderWidth = 0;
  210. #endregion
  211. #region Total 行
  212. table.Rows.Add(new TableRow());
  213. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  214. table.Rows[table.Rows.Count - 1].Cells[0].Text = "Total:";
  215. table.Rows[table.Rows.Count - 1].Cells[0].ColumnSpan = 2;
  216. table.Rows[table.Rows.Count - 1].Cells[0].HorizontalAlign = HorizontalAlign.Left;
  217. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  218. table.Rows[table.Rows.Count - 1].Cells[1].Text = "";
  219. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  220. table.Rows[table.Rows.Count - 1].Cells[2].Text = "";
  221. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  222. table.Rows[table.Rows.Count - 1].Cells[3].Text = "";
  223. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  224. table.Rows[table.Rows.Count - 1].Cells[4].Text = "";
  225. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  226. table.Rows[table.Rows.Count - 1].Cells[5].Text = "";
  227. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  228. table.Rows[table.Rows.Count - 1].Cells[6].Text = "";
  229. table.Rows[table.Rows.Count - 1].Cells.Add(new TableCell());
  230. table.Rows[table.Rows.Count - 1].Cells[7].Text = "";
  231. #endregion
  232. #endregion
  233. //设置table整体字体样式和大小
  234. table.Font.Name = "宋体";
  235. table.Font.Size = FontUnit.Parse("9.5");
  236. // render the table into the htmlwriter
  237. table.RenderControl(htw);
  238. // render the htmlwriter into the response
  239. HttpContext.Current.Response.Write(sw.ToString());
  240. HttpContext.Current.Response.Write(styleText);
  241. HttpContext.Current.Response.End();
  242. }
  243. }
  244. }
  245. public static void Export2(GridView gv)
  246. {
  247. //dataGridView1.Columns[0].HeaderText 循环列判断是否要设置为数字类型
  248. List<int> list = new List<int>();
  249. int k = 0; //序号
  250. int p = 0; //价格
  251. for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
  252. {
  253. if (gv.HeaderRow.Cells[i].Text.Contains("No.") || gv.HeaderRow.Cells[i].Text.Contains("Finished Weight(ct)") ||
  254. gv.HeaderRow.Cells[i].Text.Contains("Rough Weight(ct)") || gv.HeaderRow.Cells[i].Text.Contains("Price(USD)")
  255. || gv.HeaderRow.Cells[i].Text.Contains("Qty"))
  256. {
  257. list.Add(i);
  258. }
  259. if (gv.HeaderRow.Cells[i].Text.Contains("Price(USD)"))
  260. p = i;
  261. }
  262. foreach (GridViewRow row in gv.Rows)
  263. {
  264. int j = 0;
  265. foreach (TableCell cell in row.Cells)
  266. {
  267. if (!list.Contains(j))
  268. {
  269. cell.Style.Add("vnd.ms-excel.numberformat", "@");//给表格内容设置样式
  270. } // end foreach (TableCell cell in row.Cells)
  271. else
  272. {
  273. if (j != 0)
  274. {
  275. if (j == p)
  276. cell.Style.Add("vnd.ms-excel.numberformat", "#,##0.00");
  277. else
  278. cell.Style.Add("vnd.ms-excel.numberformat", "#,##0.000");//保留三位小数的样式,否则为默认样式
  279. }
  280. }
  281. j++;
  282. }
  283. } // end foreach (GridViewRow row in dgExcel.Rows)
  284. HttpContext.Current.Response.Clear();
  285. string styleText = @"<style> .text{mso-number-format:\@;} </style> ";
  286. string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
  287. HttpContext.Current.Response.AddHeader(
  288. "content-disposition", string.Format("attachment; filename={0}", fileName));
  289. HttpContext.Current.Response.ContentType = "application/ms-excel";
  290. HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
  291. using (StringWriter sw = new StringWriter())
  292. {
  293. using (HtmlTextWriter htw = new HtmlTextWriter(sw))
  294. {
  295. // Create a form to contain the grid
  296. Table table = new Table();
  297. table.GridLines = gv.GridLines;
  298. if (gv.HeaderRow != null)
  299. {
  300. GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
  301. table.Rows.Add(gv.HeaderRow);
  302. for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
  303. {
  304. table.Rows[0].Cells[i].BackColor = System.Drawing.Color.FromArgb(220, 240, 241);
  305. table.Rows[0].Cells[i].ForeColor = System.Drawing.Color.Black;
  306. table.Rows[0].Cells[i].Height = Unit.Pixel(24);
  307. }
  308. }
  309. // add each of the data rows to the table
  310. foreach (GridViewRow row in gv.Rows)
  311. {
  312. GridViewExportUtil.PrepareControlForExport(row);
  313. row.Height = Unit.Pixel(22);
  314. row.HorizontalAlign = HorizontalAlign.Center;
  315. table.Rows.Add(row);
  316. }
  317. // add the footer row to the table
  318. if (gv.FooterRow != null)
  319. {
  320. GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
  321. table.Rows.Add(gv.FooterRow);
  322. }
  323. //设置table整体字体样式和大小
  324. table.Font.Name = "宋体";
  325. table.Font.Size = FontUnit.Parse("9.5");
  326. // render the table into the htmlwriter
  327. table.RenderControl(htw);
  328. // render the htmlwriter into the response
  329. HttpContext.Current.Response.Write(sw.ToString());
  330. HttpContext.Current.Response.Write(styleText);
  331. HttpContext.Current.Response.End();
  332. }
  333. }
  334. }
  335. public static void Export(DataTable dt, string PreSellNo)
  336. {
  337. using (GridView gv = new GridView())
  338. {
  339. DataTable dtExport = new DataTable();
  340. dtExport.Columns.Add("No.", Type.GetType("System.Int32"));
  341. dtExport.Columns.Add("Product No.", Type.GetType("System.String"));
  342. dtExport.Columns.Add("Measurement", Type.GetType("System.String"));
  343. dtExport.Columns.Add("Finished Weight(ct)", Type.GetType("System.Decimal"));
  344. dtExport.Columns.Add("Rough Weight(ct)", Type.GetType("System.Decimal"));
  345. dtExport.Columns.Add("Price(USD)", Type.GetType("System.Decimal"));
  346. dtExport.Columns.Add("Discount(%)", Type.GetType("System.String"));
  347. dtExport.Columns.Add("Amount(USD)", Type.GetType("System.Decimal"));
  348. dtExport.Columns.Add("Shape", Type.GetType("System.String"));
  349. int number = 1;
  350. //for (int i = 0; i < 3; i++)
  351. //{
  352. // DataRow rtop = dtExport.NewRow();
  353. // dtExport.Rows.Add(rtop);
  354. //}
  355. foreach (DataRow row in dt.Rows)
  356. {
  357. DataRow r = dtExport.NewRow();
  358. r["No."] = number;
  359. r["Product No."] = row["ProductSN"].ToString();
  360. r["Measurement"] = row["Measurement"].ToString();
  361. r["Finished Weight(ct)"] = row["Weight"].ToString();
  362. r["Rough Weight(ct)"] = row["GrossWeight"].ToString();
  363. r["Price(USD)"] = string.IsNullOrEmpty(row["Price"].ToString()) ? 0 : decimal.Parse(row["Price"].ToString());
  364. r["Discount(%)"] = row["Discount"].ToString();
  365. r["Amount(USD)"] = string.IsNullOrEmpty(row["Amount"].ToString()) ? 0 : decimal.Parse(row["Amount"].ToString());
  366. r["Shape"] = row["Shape"].ToString();
  367. dtExport.Rows.Add(r);
  368. number++;
  369. }
  370. gv.DataSource = dtExport;
  371. gv.DataBind();
  372. Export(gv, PreSellNo);
  373. }
  374. }
  375. public static void Export2(DataTable dt)
  376. {
  377. using (GridView gv = new GridView())
  378. {
  379. DataTable dtExport = new DataTable();
  380. dtExport.Columns.Add("No.", Type.GetType("System.Int32"));
  381. dtExport.Columns.Add("Product No.", Type.GetType("System.String"));
  382. dtExport.Columns.Add("Measurement", Type.GetType("System.String"));
  383. dtExport.Columns.Add("Sort", Type.GetType("System.String"));
  384. dtExport.Columns.Add("Location", Type.GetType("System.String"));
  385. dtExport.Columns.Add("Qty", Type.GetType("System.Int32"));
  386. dtExport.Columns.Add("Finished Weight(ct)", Type.GetType("System.Decimal"));
  387. dtExport.Columns.Add("Rough Weight(ct)", Type.GetType("System.Decimal"));
  388. dtExport.Columns.Add("Price(USD)", Type.GetType("System.Decimal"));
  389. dtExport.Columns.Add("Shape", Type.GetType("System.String"));
  390. dtExport.Columns.Add("CertificateNo", Type.GetType("System.String"));
  391. dtExport.Columns.Add("Color", Type.GetType("System.String"));
  392. dtExport.Columns.Add("Clarity", Type.GetType("System.String"));
  393. dtExport.Columns.Add("Polish", Type.GetType("System.String"));
  394. int number = 1;
  395. foreach (DataRow row in dt.Rows)
  396. {
  397. DataRow r = dtExport.NewRow();
  398. r["No."] = number;
  399. r["Product No."] = row["ProductSN"].ToString();
  400. r["Measurement"] = row["Measurement"].ToString();
  401. r["Sort"] = row["Sort"].ToString();
  402. r["Location"] = row["Location"].ToString();
  403. r["Qty"] = row["Qty"].ToString();
  404. r["Finished Weight(ct)"] = string.IsNullOrEmpty(row["FinishedWeight"].ToString()) ? "0" : row["FinishedWeight"].ToString();
  405. r["Rough Weight(ct)"] = string.IsNullOrEmpty(row["RoughWeight"].ToString()) ? "0" : row["RoughWeight"].ToString();
  406. r["Price(USD)"] = string.IsNullOrEmpty(row["Price"].ToString()) ? 0 : decimal.Parse(row["Price"].ToString());
  407. r["Shape"] = row["Shape"].ToString();
  408. r["CertificateNo"] = row["CertificateNo"].ToString();
  409. r["Color"] = row["Color"].ToString();
  410. r["Clarity"] = row["Clarity"].ToString();
  411. r["Polish"] = row["Polish"].ToString();
  412. dtExport.Rows.Add(r);
  413. number++;
  414. }
  415. gv.DataSource = dtExport;
  416. gv.DataBind();
  417. Export2(gv);
  418. }
  419. }
  420. /// <summary>
  421. /// Replace any of the contained controls with literals
  422. /// </summary>
  423. /// <param name="control"></param>
  424. private static void PrepareControlForExport(Control control)
  425. {
  426. for (int i = 0; i < control.Controls.Count; i++)
  427. {
  428. Control current = control.Controls[i];
  429. if (current is LinkButton)
  430. {
  431. control.Controls.Remove(current);
  432. control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
  433. }
  434. else if (current is ImageButton)
  435. {
  436. control.Controls.Remove(current);
  437. control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
  438. }
  439. else if (current is HyperLink)
  440. {
  441. control.Controls.Remove(current);
  442. control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
  443. }
  444. else if (current is DropDownList)
  445. {
  446. control.Controls.Remove(current);
  447. control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
  448. }
  449. else if (current is CheckBox)
  450. {
  451. control.Controls.Remove(current);
  452. control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
  453. }
  454. if (current.HasControls())
  455. {
  456. GridViewExportUtil.PrepareControlForExport(current);
  457. }
  458. }
  459. }
  460. }
  461. public class AsposeCell
  462. {
  463. public static void Export(DataTable dt)
  464. {
  465. var name = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random(DateTime.Now.Second).Next(10000) + ".xls";
  466. MemoryStream ms = OutFileToStream(dt);
  467. HttpContext.Current.Response.Clear();
  468. HttpContext.Current.Response.ContentType = "application/ms-excel";
  469. HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
  470. HttpContext.Current.Response.Charset = "utf-8";
  471. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
  472. HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().LongLength.ToString());
  473. HttpContext.Current.Response.BinaryWrite(ms.ToArray());
  474. HttpContext.Current.Response.Flush();
  475. HttpContext.Current.Response.Clear();
  476. HttpContext.Current.Response.End();
  477. }
  478. public static void Export(byte[] ms)
  479. {
  480. var name = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random(DateTime.Now.Second).Next(10000) + ".pdf";
  481. HttpContext.Current.Response.Clear();
  482. HttpContext.Current.Response.ContentType = "application/pdf";
  483. HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
  484. HttpContext.Current.Response.Charset = "utf-8";
  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 MemoryStream OutFileToStream(DataTable dt)
  493. {
  494. Workbook workbook = new Workbook(); //工作簿
  495. workbook.Worksheets.Clear();
  496. for (int j = 0; j < System.Math.Ceiling((dt.Rows.Count / (double)65534)); j++)
  497. {
  498. workbook.Worksheets.Add("" + j);
  499. Worksheet sheet = workbook.Worksheets[j];
  500. Cells cells = sheet.Cells;//单元格
  501. //为标题设置样式
  502. Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式
  503. styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  504. styleTitle.Font.Name = "宋体";//文字字体
  505. styleTitle.Font.Size = 18;//文字大小
  506. styleTitle.Font.IsBold = true;//粗体
  507. //样式2
  508. Aspose.Cells.Style style2 = workbook.Styles[workbook.Styles.Add()];//新增样式
  509. style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  510. style2.Font.Name = "宋体";//文字字体
  511. style2.Font.Size = 14;//文字大小
  512. style2.Font.IsBold = true;//粗体
  513. style2.IsTextWrapped = false;//单元格内容自动换行
  514. //样式3
  515. Aspose.Cells.Style style3 = workbook.Styles[workbook.Styles.Add()];//新增样式
  516. style3.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  517. style3.Font.Name = "宋体";//文字字体
  518. style3.Font.Size = 12;//文字大小
  519. style2.IsTextWrapped = false;//单元格内容自动换行
  520. int Colnum = dt.Columns.Count;//表格列数
  521. int Rownum = dt.Rows.Count;//表格行数
  522. //生成行2 列名行
  523. for (int i = 0; i < Colnum; i++)
  524. {
  525. cells[0, i].PutValue(dt.Columns[i].ColumnName);
  526. cells[0, i].SetStyle(style2);
  527. cells.SetRowHeight(0, 25);
  528. for (int col = 0; col < Colnum; col++)
  529. {
  530. sheet.AutoFitColumn(col, 0, Rownum);
  531. }
  532. for (int col = 0; col < Colnum; col++)
  533. {
  534. cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 30);
  535. }
  536. }
  537. //生成数据行
  538. for (int i = 0; i < 65534; i++)
  539. {
  540. if ((j * 65534 + i) >= Rownum)
  541. {
  542. break;
  543. }
  544. for (int k = 0; k < Colnum; k++)
  545. {
  546. cells[1 + i, k].PutValue(dt.Rows[j * 65534 + i][k].ToString());
  547. cells[1 + i, k].SetStyle(style3);
  548. }
  549. cells.SetRowHeight(1 + i, 24);
  550. }
  551. }
  552. MemoryStream ms = workbook.SaveToStream();
  553. return ms;
  554. }
  555. }
  556. public class FileToExcel
  557. {
  558. /// <summary>
  559. /// Excel导入成Datable
  560. /// </summary>
  561. /// <param name="file">导入路径(包含文件名与扩展名)</param>
  562. /// <returns></returns>
  563. public static DataTable ExcelToTable(string file)
  564. {
  565. DataTable dt = new DataTable();
  566. IWorkbook workbook;
  567. try
  568. {
  569. string fileExt = Path.GetExtension(file).ToLower();
  570. using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
  571. {
  572. //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
  573. if (fileExt == ".xlsx")
  574. { workbook = new XSSFWorkbook(fs); }
  575. else if (fileExt == ".xls")
  576. { workbook = new HSSFWorkbook(fs); }
  577. else { workbook = null; }
  578. if (workbook == null) { return null; }
  579. ISheet sheet = workbook.GetSheetAt(0);
  580. //表头
  581. IRow header = sheet.GetRow(sheet.FirstRowNum);
  582. List<int> columns = new List<int>();
  583. for (int i = 0; i < header.LastCellNum; i++)
  584. {
  585. ICell cell = header.GetCell(i);
  586. var FillForegroundColor = cell.CellStyle.FillForegroundColor.ToString();
  587. object obj = GetValueType(cell);
  588. if (obj == null || obj.ToString() == string.Empty)
  589. {
  590. //dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
  591. }
  592. else
  593. {
  594. DataColumn dc = new DataColumn(obj.ToString());
  595. if (FillForegroundColor == "15")
  596. dc.AllowDBNull = false;
  597. else
  598. dc.AllowDBNull = true;
  599. dt.Columns.Add(dc);
  600. columns.Add(i);
  601. }
  602. }
  603. //判断模板栏位是否正确 略
  604. #region 判断模板是否正确
  605. #endregion
  606. //end 判断模板栏位正确
  607. //数据
  608. for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
  609. {
  610. DataRow dr = dt.NewRow();
  611. bool hasValue = false;
  612. foreach (int j in columns)
  613. {
  614. dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
  615. if (!string.IsNullOrWhiteSpace(dr[j].ToString()))
  616. {
  617. hasValue = true;
  618. }
  619. else if (!dt.Columns[j].AllowDBNull)
  620. {
  621. string msg = "第 " + i + " 行,列" + dt.Columns[j].ColumnName + "没有输入值";
  622. throw new Exception(msg);
  623. }
  624. }
  625. if (hasValue)
  626. {
  627. dt.Rows.Add(dr);
  628. }
  629. }
  630. }
  631. return dt;
  632. }
  633. catch (Exception ex)
  634. {
  635. throw ex;
  636. }
  637. }
  638. /// <summary>
  639. /// 获取单元格类型
  640. /// </summary>
  641. /// <param name="cell"></param>
  642. /// <returns></returns>
  643. public static object GetValueType(ICell cell)
  644. {
  645. if (cell == null)
  646. return null;
  647. switch (cell.CellType)
  648. {
  649. case CellType.Blank: //BLANK:
  650. return null;
  651. case CellType.Boolean: //BOOLEAN:
  652. return cell.BooleanCellValue;
  653. case CellType.Numeric:
  654. //NUMERIC:
  655. //{
  656. // var time= cell.DateCellValue;
  657. // if (1==1)
  658. // return cell.NumericCellValue;
  659. //}
  660. if (HSSFDateUtil.IsCellDateFormatted(cell))
  661. {
  662. return cell.DateCellValue;
  663. }
  664. else
  665. {
  666. return cell.NumericCellValue;
  667. }
  668. case CellType.String: //STRING:
  669. return cell.StringCellValue;
  670. case CellType.Error: //ERROR:
  671. return cell.ErrorCellValue;
  672. case CellType.Formula: //FORMULA:
  673. default:
  674. return "=" + cell.CellFormula;
  675. }
  676. return cell.StringCellValue;
  677. }
  678. }
  679. }