鄂尔多斯-招源科技

NPOIHelper.cs 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. 
  2. using System;
  3. using System.Data;
  4. using System.IO;
  5. using System.Text;
  6. using System.Web;
  7. using NPOI.HSSF.UserModel;
  8. using NPOI.SS.UserModel;
  9. using NPOI.SS.Util;
  10. using NPOI.XSSF.UserModel;
  11. namespace CallCenter.Utility
  12. {
  13. public class NPOIHelper
  14. {
  15. private string _title;
  16. private string _sheetName;
  17. private string _filePath;
  18. /// <summary>
  19. /// 导出到Excel
  20. /// </summary>
  21. /// <param name="table"></param>
  22. /// <returns></returns>
  23. public bool ToExcel(DataTable table, string[] columns = null)
  24. {
  25. FileStream fs = new FileStream(this._filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  26. IWorkbook workBook = new HSSFWorkbook();
  27. if (string.IsNullOrWhiteSpace(this._sheetName))
  28. {
  29. this._sheetName = "sheet1";
  30. }
  31. ISheet sheet = workBook.CreateSheet(this._sheetName);
  32. //处理表格标题
  33. IRow row = sheet.CreateRow(0);
  34. row.CreateCell(0).SetCellValue(this._title);
  35. sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, table.Columns.Count - 1));
  36. row.Height = 500;
  37. ICellStyle cellStyle = workBook.CreateCellStyle();
  38. IFont font = workBook.CreateFont();
  39. font.FontName = "微软雅黑";
  40. font.FontHeightInPoints = 17;
  41. cellStyle.SetFont(font);
  42. cellStyle.VerticalAlignment = VerticalAlignment.Center;
  43. cellStyle.Alignment = HorizontalAlignment.Center;
  44. row.Cells[0].CellStyle = cellStyle;
  45. //处理表格列头
  46. row = sheet.CreateRow(1);
  47. if (columns == null)
  48. {
  49. for (int i = 0; i < table.Columns.Count; i++)
  50. {
  51. row.CreateCell(i).SetCellValue(table.Columns[i].ColumnName);
  52. row.Height = 350;
  53. sheet.AutoSizeColumn(i);
  54. }
  55. }
  56. else
  57. {
  58. for (int i = 0; i < columns.Length; i++)
  59. {
  60. row.CreateCell(i).SetCellValue(columns[i]);
  61. row.Height = 350;
  62. sheet.AutoSizeColumn(i);
  63. }
  64. }
  65. //处理数据内容
  66. for (int i = 0; i < table.Rows.Count; i++)
  67. {
  68. row = sheet.CreateRow(2 + i);
  69. row.Height = 250;
  70. for (int j = 0; j < table.Columns.Count; j++)
  71. {
  72. row.CreateCell(j).SetCellValue(table.Rows[i][j].ToString());
  73. sheet.SetColumnWidth(j, 256 * 15);
  74. }
  75. }
  76. //写入数据流
  77. workBook.Write(fs);
  78. fs.Flush();
  79. fs.Close();
  80. return true;
  81. }
  82. /// <summary>
  83. /// 导出到Excel
  84. /// </summary>
  85. /// <param name="table"></param>
  86. /// <param name="title"></param>
  87. /// <param name="sheetName">空字符串或null的话默认sheet1</param>
  88. /// <param name="columns">自定义表格列头,默认null</param>
  89. /// <returns></returns>
  90. public bool ToExcel(DataTable table, string title, string sheetName, string filePath, string[] columns = null)
  91. {
  92. this._title = title;
  93. this._sheetName = sheetName;
  94. this._filePath = filePath;
  95. return ToExcel(table, columns);
  96. }
  97. /// <summary>
  98. /// 弹出下载框导出excel
  99. /// </summary>
  100. /// <param name="Name"></param>
  101. /// <param name="dt"></param>
  102. /// <returns></returns>
  103. public string ExportToExcel_old(string Name, DataTable dt, string[] cols = null)
  104. {
  105. try
  106. {
  107. HSSFWorkbook workbook = new HSSFWorkbook();
  108. ISheet sheet = workbook.CreateSheet("Sheet1");
  109. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  110. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  111. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  112. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  113. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  114. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  115. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  116. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  117. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  118. //字体
  119. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  120. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  121. headerfont.FontHeightInPoints = 12;
  122. HeadercellStyle.SetFont(headerfont);
  123. //用column name 作为列名
  124. int icolIndex = 0;
  125. IRow headerRow = sheet.CreateRow(0);
  126. if (cols == null || (cols != null && cols.Length == 0))
  127. {
  128. foreach (DataColumn dc in dt.Columns)
  129. {
  130. ICell cell = headerRow.CreateCell(icolIndex);
  131. cell.SetCellValue(dc.ColumnName);
  132. cell.CellStyle = HeadercellStyle;
  133. icolIndex++;
  134. }
  135. }
  136. else
  137. {
  138. foreach (string dc in cols)
  139. {
  140. ICell cell = headerRow.CreateCell(icolIndex);
  141. cell.SetCellValue(dc);
  142. cell.CellStyle = HeadercellStyle;
  143. icolIndex++;
  144. }
  145. }
  146. ICellStyle cellStyle = workbook.CreateCellStyle();
  147. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  148. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  149. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  150. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  151. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  152. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  153. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  154. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  155. cellStyle.SetFont(cellfont);
  156. if (dt.Rows.Count > 0)
  157. {
  158. //建立内容行
  159. int iRowIndex = 0;
  160. foreach (DataRow dr in dt.Rows)
  161. {
  162. int iCellIndex = 0;
  163. IRow irow = sheet.CreateRow(iRowIndex + 1);
  164. for (int i = 0; i < dt.Columns.Count; i++)
  165. {
  166. string strsj = string.Empty;
  167. if (dr[i] != null)
  168. {
  169. strsj = dr[i].ToString();
  170. }
  171. ICell cell = irow.CreateCell(iCellIndex);
  172. cell.SetCellValue(strsj);
  173. cell.CellStyle = cellStyle;
  174. iCellIndex++;
  175. }
  176. iRowIndex++;
  177. }
  178. //自适应列宽度
  179. for (int i = 0; i < icolIndex; i++)
  180. {
  181. sheet.AutoSizeColumn(i);
  182. }
  183. }
  184. using (MemoryStream ms = new MemoryStream())
  185. {
  186. workbook.Write(ms);
  187. HttpContext curContext = HttpContext.Current;
  188. // 设置编码和附件格式
  189. curContext.Response.ContentType = "application/vnd.ms-excel";
  190. curContext.Response.ContentEncoding = Encoding.UTF8;
  191. curContext.Response.Charset = "";
  192. curContext.Response.AppendHeader("Content-Disposition",
  193. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  194. curContext.Response.BinaryWrite(ms.GetBuffer());
  195. workbook = null;
  196. ms.Close();
  197. ms.Dispose();
  198. curContext.Response.End();
  199. }
  200. return "";
  201. }
  202. catch
  203. {
  204. return "导出失败!";
  205. }
  206. }
  207. /// <summary>
  208. /// 弹出下载框导出excel => 创建多个Sheet:例如sheet1,sheet2...
  209. /// </summary>
  210. /// <param name="Name"></param>
  211. /// <param name="dt"></param>
  212. /// <returns></returns>
  213. public string ExportToExcel(string Name, DataTable dt, string[] cols = null)
  214. {
  215. try
  216. {
  217. HSSFWorkbook workbook = new HSSFWorkbook();
  218. //ISheet sheet = workbook.CreateSheet("Sheet1");
  219. //数据总数
  220. int count = dt.Rows.Count;
  221. //注意:1、Excel2003及以前版本65536行,256列; 2、Excel2007、2010版本1048576行,16384列
  222. int sheetpage = 50000; //这里设置5w条
  223. //向上取整
  224. int sheetindexcount = int.Parse(Math.Ceiling(Convert.ToDecimal((double)count / sheetpage)).ToString());
  225. if(sheetindexcount == 0)
  226. sheetindexcount = 1;
  227. for (int n = 1; n <= sheetindexcount; n++)
  228. {
  229. ISheet sheet = workbook.CreateSheet("Sheet" + n);
  230. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  231. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  232. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  233. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  234. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  235. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  236. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  237. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  238. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  239. //字体
  240. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  241. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  242. headerfont.FontHeightInPoints = 12;
  243. HeadercellStyle.SetFont(headerfont);
  244. //用column name 作为列名
  245. int icolIndex = 0;
  246. IRow headerRow = sheet.CreateRow(0);
  247. if (cols == null || (cols != null && cols.Length == 0))
  248. {
  249. foreach (DataColumn dc in dt.Columns)
  250. {
  251. ICell cell = headerRow.CreateCell(icolIndex);
  252. cell.SetCellValue(dc.ColumnName);
  253. cell.CellStyle = HeadercellStyle;
  254. icolIndex++;
  255. }
  256. }
  257. else
  258. {
  259. foreach (string dc in cols)
  260. {
  261. ICell cell = headerRow.CreateCell(icolIndex);
  262. cell.SetCellValue(dc);
  263. cell.CellStyle = HeadercellStyle;
  264. icolIndex++;
  265. }
  266. }
  267. ICellStyle cellStyle = workbook.CreateCellStyle();
  268. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  269. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  270. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  271. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  272. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  273. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  274. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  275. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  276. cellStyle.SetFont(cellfont);
  277. if (dt.Rows.Count > 0)
  278. {
  279. //建立内容行
  280. int iRowIndex = 0;
  281. #region 修改不用
  282. //foreach (DataRow dr in dt.Rows)
  283. //{
  284. // int iCellIndex = 0;
  285. // IRow irow = sheet.CreateRow(iRowIndex + 1);
  286. // for (int i = 0; i < dt.Columns.Count; i++)
  287. // {
  288. // string strsj = string.Empty;
  289. // if (dr[i] != null)
  290. // {
  291. // strsj = dr[i].ToString();
  292. // }
  293. // ICell cell = irow.CreateCell(iCellIndex);
  294. // cell.SetCellValue(strsj);
  295. // cell.CellStyle = cellStyle;
  296. // iCellIndex++;
  297. // }
  298. // iRowIndex++;
  299. //}
  300. #endregion
  301. int startcount = (n - 1) * sheetpage;
  302. int endcount = n * sheetpage;
  303. if (sheetindexcount == n)
  304. endcount = count;
  305. //for (int x = 0; x < dt.Rows.Count; x++)
  306. for (int x = startcount; x < endcount; x++)
  307. {
  308. int iCellIndex = 0;
  309. IRow irow = sheet.CreateRow(iRowIndex + 1);
  310. for (int i = 0; i < dt.Columns.Count; i++)
  311. {
  312. string strsj = string.Empty;
  313. if (dt.Rows[x][i] != null)
  314. {
  315. strsj = dt.Rows[x][i].ToString();
  316. }
  317. ICell cell = irow.CreateCell(iCellIndex);
  318. cell.SetCellValue(strsj);
  319. cell.CellStyle = cellStyle;
  320. iCellIndex++;
  321. }
  322. iRowIndex++;
  323. }
  324. //自适应列宽度
  325. for (int i = 0; i < icolIndex; i++)
  326. {
  327. sheet.AutoSizeColumn(i);
  328. }
  329. }
  330. }
  331. using (MemoryStream ms = new MemoryStream())
  332. {
  333. workbook.Write(ms);
  334. HttpContext curContext = HttpContext.Current;
  335. // 设置编码和附件格式
  336. curContext.Response.ContentType = "application/vnd.ms-excel";
  337. curContext.Response.ContentEncoding = Encoding.UTF8;
  338. curContext.Response.Charset = "";
  339. curContext.Response.AppendHeader("Content-Disposition",
  340. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  341. curContext.Response.BinaryWrite(ms.GetBuffer());
  342. workbook = null;
  343. ms.Close();
  344. ms.Dispose();
  345. curContext.Response.End();
  346. }
  347. return "";
  348. }
  349. catch(Exception ex)
  350. {
  351. return "导出失败!" + ex.Message;
  352. }
  353. }
  354. /// <summary>
  355. /// 创建Sheet
  356. /// </summary>
  357. /// <param name="workBook"></param>
  358. /// <param name="sheetName"></param>
  359. /// <returns></returns>
  360. public ISheet CreateSheet(HSSFWorkbook workBook, string sheetName)
  361. {
  362. ISheet sheet = workBook.CreateSheet(sheetName);
  363. IRow RowHead = sheet.CreateRow(0);
  364. for (int iColumnIndex = 0; iColumnIndex < 10; iColumnIndex++)
  365. {
  366. RowHead.CreateCell(iColumnIndex).SetCellValue(Guid.NewGuid().ToString());
  367. }
  368. for (int iRowIndex = 0; iRowIndex < 20; iRowIndex++)
  369. {
  370. IRow RowBody = sheet.CreateRow(iRowIndex + 1);
  371. for (int iColumnIndex = 0; iColumnIndex < 10; iColumnIndex++)
  372. {
  373. RowBody.CreateCell(iColumnIndex).SetCellValue(DateTime.Now.Millisecond);
  374. sheet.AutoSizeColumn(iColumnIndex);
  375. }
  376. }
  377. return sheet;
  378. }
  379. /// <summary>
  380. /// 导入excel转换为datatable
  381. /// </summary>
  382. /// <param name="upfile"></param>
  383. /// <param name="headrow"></param>
  384. /// <returns></returns>
  385. public DataTable ExcelToTable(HttpPostedFile upfile, int headrow)
  386. {
  387. DataTable dt = new DataTable();
  388. IWorkbook workbook = null;
  389. Stream stream = upfile.InputStream;
  390. string suffix = upfile.FileName.Substring(upfile.FileName.LastIndexOf(".") + 1).ToLower();
  391. if (suffix == "xlsx") // 2007版本
  392. {
  393. workbook = new XSSFWorkbook(stream);
  394. }
  395. else if (suffix == "xls") // 2003版本
  396. {
  397. workbook = new HSSFWorkbook(stream);
  398. }
  399. //获取excel的第一个sheet
  400. ISheet sheet = workbook.GetSheetAt(0);
  401. //获取sheet的第一行
  402. IRow headerRow = sheet.GetRow(headrow);
  403. //一行最后一个方格的编号 即总的列数
  404. int cellCount = headerRow.LastCellNum;
  405. //最后一列的标号 即总的行数
  406. int rowCount = sheet.LastRowNum;
  407. //列名
  408. for (int i = 0; i < cellCount; i++)
  409. {
  410. dt.Columns.Add(headerRow.GetCell(i).ToString());
  411. }
  412. for (int i = (sheet.FirstRowNum + headrow); i <= sheet.LastRowNum; i++)
  413. {
  414. DataRow dr = dt.NewRow();
  415. IRow row = sheet.GetRow(i);
  416. for (int j = row.FirstCellNum; j < cellCount; j++)
  417. {
  418. if (row.GetCell(j) != null)
  419. {
  420. dr[j] = row.GetCell(j).ToString();
  421. }
  422. }
  423. dt.Rows.Add(dr);
  424. }
  425. sheet = null;
  426. workbook = null;
  427. return dt;
  428. }
  429. /// <summary>
  430. /// 上传excel文件,并且读取excel文件转换为datatable, HttpPostedFileBase
  431. /// </summary>
  432. /// <param name="upfile"></param>
  433. /// <param name="headrow"></param>
  434. /// <returns></returns>
  435. public DataTable ExcelToTable(HttpPostedFileBase upfile, int headrow, out string filePath)
  436. {
  437. var ext = upfile.FileName.Substring(upfile.FileName.LastIndexOf(".") + 1).ToLower();
  438. var foldPath = $"{HttpContext.Current.Request.ApplicationPath}\\ExcelData\\{ DateTime.Now.ToString("yyyyMM")}";
  439. var server = HttpContext.Current.Server;
  440. if (!Directory.Exists(server.MapPath(foldPath)))
  441. {
  442. Directory.CreateDirectory(server.MapPath(foldPath));
  443. }
  444. filePath = server.MapPath($"{foldPath}\\") + Guid.NewGuid().ToString("N") + "." + ext;
  445. upfile.SaveAs(filePath);
  446. DataTable dt = new DataTable();
  447. IWorkbook workbook = null;
  448. Stream stream = upfile.InputStream;
  449. string suffix = ext;
  450. if (suffix == "xlsx") // 2007版本
  451. {
  452. workbook = new XSSFWorkbook(stream);
  453. }
  454. else if (suffix == "xls") // 2003版本
  455. {
  456. workbook = new HSSFWorkbook(stream);
  457. }
  458. //获取excel的第一个sheet
  459. ISheet sheet = workbook.GetSheetAt(0);
  460. //获取sheet的第一行
  461. IRow headerRow = sheet.GetRow(headrow);
  462. //一行最后一个方格的编号 即总的列数
  463. int cellCount = headerRow.LastCellNum;
  464. //最后一列的标号 即总的行数
  465. int rowCount = sheet.LastRowNum;
  466. //列名
  467. for (int i = 0; i < cellCount; i++)
  468. {
  469. dt.Columns.Add(headerRow.GetCell(i).ToString());
  470. }
  471. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  472. {
  473. DataRow dr = dt.NewRow();
  474. IRow row = sheet.GetRow(i);
  475. for (int j = row.FirstCellNum; j < cellCount; j++)
  476. {
  477. if (row.GetCell(j) != null)
  478. {
  479. dr[j] = row.GetCell(j).ToString();
  480. }
  481. }
  482. dt.Rows.Add(dr);
  483. }
  484. sheet = null;
  485. workbook = null;
  486. return dt;
  487. }
  488. /// <summary>
  489. /// 导入excel转换为datatable
  490. /// </summary>
  491. /// <param name="upfile"></param>
  492. /// <param name="headrow"></param>
  493. /// <returns></returns>
  494. public DataTable ExcelToTable(string fileName, int headrow)
  495. {
  496. DataTable dt = new DataTable();
  497. IWorkbook workbook = null;
  498. Stream stream = new FileStream(fileName, FileMode.OpenOrCreate);
  499. string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
  500. if (suffix == "xlsx") // 2007版本
  501. {
  502. workbook = new XSSFWorkbook(stream);
  503. }
  504. else if (suffix == "xls") // 2003版本
  505. {
  506. workbook = new HSSFWorkbook(stream);
  507. }
  508. //获取excel的第一个sheet
  509. ISheet sheet = workbook.GetSheetAt(0);
  510. //获取sheet的第一行
  511. IRow headerRow = sheet.GetRow(headrow);
  512. //一行最后一个方格的编号 即总的列数
  513. int cellCount = headerRow.LastCellNum;
  514. //最后一列的标号 即总的行数
  515. int rowCount = sheet.LastRowNum;
  516. //列名
  517. for (int i = 0; i < cellCount; i++)
  518. {
  519. dt.Columns.Add(headerRow.GetCell(i).ToString());
  520. }
  521. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  522. {
  523. DataRow dr = dt.NewRow();
  524. IRow row = sheet.GetRow(i);
  525. for (int j = row.FirstCellNum; j < cellCount; j++)
  526. {
  527. if (row.GetCell(j) != null)
  528. {
  529. dr[j] = row.GetCell(j).ToString();
  530. }
  531. }
  532. dt.Rows.Add(dr);
  533. }
  534. sheet = null;
  535. workbook = null;
  536. return dt;
  537. }
  538. }
  539. }