纽威
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.

869 lines
38 KiB

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