Няма описание

NPOIHelper.cs 23KB

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