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.

849 lines
36 KiB

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