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

893 lines
39 KiB

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