鄂尔多斯-招源科技

NPOIHelper.cs 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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(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转换为datatable
  209. /// </summary>
  210. /// <param name="upfile"></param>
  211. /// <param name="headrow"></param>
  212. /// <returns></returns>
  213. public DataTable ExcelToTable(HttpPostedFile upfile, int headrow)
  214. {
  215. DataTable dt = new DataTable();
  216. IWorkbook workbook = null;
  217. Stream stream = upfile.InputStream;
  218. string suffix = upfile.FileName.Substring(upfile.FileName.LastIndexOf(".") + 1).ToLower();
  219. if (suffix == "xlsx") // 2007版本
  220. {
  221. workbook = new XSSFWorkbook(stream);
  222. }
  223. else if (suffix == "xls") // 2003版本
  224. {
  225. workbook = new HSSFWorkbook(stream);
  226. }
  227. //获取excel的第一个sheet
  228. ISheet sheet = workbook.GetSheetAt(0);
  229. //获取sheet的第一行
  230. IRow headerRow = sheet.GetRow(headrow);
  231. //一行最后一个方格的编号 即总的列数
  232. int cellCount = headerRow.LastCellNum;
  233. //最后一列的标号 即总的行数
  234. int rowCount = sheet.LastRowNum;
  235. //列名
  236. for (int i = 0; i < cellCount; i++)
  237. {
  238. dt.Columns.Add(headerRow.GetCell(i).ToString());
  239. }
  240. for (int i = (sheet.FirstRowNum + headrow); i <= sheet.LastRowNum; i++)
  241. {
  242. DataRow dr = dt.NewRow();
  243. IRow row = sheet.GetRow(i);
  244. for (int j = row.FirstCellNum; j < cellCount; j++)
  245. {
  246. if (row.GetCell(j) != null)
  247. {
  248. dr[j] = row.GetCell(j).ToString();
  249. }
  250. }
  251. dt.Rows.Add(dr);
  252. }
  253. sheet = null;
  254. workbook = null;
  255. return dt;
  256. }
  257. /// <summary>
  258. /// 上传excel文件,并且读取excel文件转换为datatable, HttpPostedFileBase
  259. /// </summary>
  260. /// <param name="upfile"></param>
  261. /// <param name="headrow"></param>
  262. /// <returns></returns>
  263. public DataTable ExcelToTable(HttpPostedFileBase upfile, int headrow, out string filePath)
  264. {
  265. var ext = upfile.FileName.Substring(upfile.FileName.LastIndexOf(".") + 1).ToLower();
  266. var foldPath = $"{HttpContext.Current.Request.ApplicationPath}\\ExcelData\\{ DateTime.Now.ToString("yyyyMM")}";
  267. var server = HttpContext.Current.Server;
  268. if (!Directory.Exists(server.MapPath(foldPath)))
  269. {
  270. Directory.CreateDirectory(server.MapPath(foldPath));
  271. }
  272. filePath = server.MapPath($"{foldPath}\\") + Guid.NewGuid().ToString("N") + "." + ext;
  273. upfile.SaveAs(filePath);
  274. DataTable dt = new DataTable();
  275. IWorkbook workbook = null;
  276. Stream stream = upfile.InputStream;
  277. string suffix = ext;
  278. if (suffix == "xlsx") // 2007版本
  279. {
  280. workbook = new XSSFWorkbook(stream);
  281. }
  282. else if (suffix == "xls") // 2003版本
  283. {
  284. workbook = new HSSFWorkbook(stream);
  285. }
  286. //获取excel的第一个sheet
  287. ISheet sheet = workbook.GetSheetAt(0);
  288. //获取sheet的第一行
  289. IRow headerRow = sheet.GetRow(headrow);
  290. //一行最后一个方格的编号 即总的列数
  291. int cellCount = headerRow.LastCellNum;
  292. //最后一列的标号 即总的行数
  293. int rowCount = sheet.LastRowNum;
  294. //列名
  295. for (int i = 0; i < cellCount; i++)
  296. {
  297. dt.Columns.Add(headerRow.GetCell(i).ToString());
  298. }
  299. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  300. {
  301. DataRow dr = dt.NewRow();
  302. IRow row = sheet.GetRow(i);
  303. for (int j = row.FirstCellNum; j < cellCount; j++)
  304. {
  305. if (row.GetCell(j) != null)
  306. {
  307. dr[j] = row.GetCell(j).ToString();
  308. }
  309. }
  310. dt.Rows.Add(dr);
  311. }
  312. sheet = null;
  313. workbook = null;
  314. return dt;
  315. }
  316. /// <summary>
  317. /// 导入excel转换为datatable
  318. /// </summary>
  319. /// <param name="upfile"></param>
  320. /// <param name="headrow"></param>
  321. /// <returns></returns>
  322. public DataTable ExcelToTable(string fileName, int headrow)
  323. {
  324. DataTable dt = new DataTable();
  325. IWorkbook workbook = null;
  326. Stream stream = new FileStream(fileName, FileMode.OpenOrCreate);
  327. string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
  328. if (suffix == "xlsx") // 2007版本
  329. {
  330. workbook = new XSSFWorkbook(stream);
  331. }
  332. else if (suffix == "xls") // 2003版本
  333. {
  334. workbook = new HSSFWorkbook(stream);
  335. }
  336. //获取excel的第一个sheet
  337. ISheet sheet = workbook.GetSheetAt(0);
  338. //获取sheet的第一行
  339. IRow headerRow = sheet.GetRow(headrow);
  340. //一行最后一个方格的编号 即总的列数
  341. int cellCount = headerRow.LastCellNum;
  342. //最后一列的标号 即总的行数
  343. int rowCount = sheet.LastRowNum;
  344. //列名
  345. for (int i = 0; i < cellCount; i++)
  346. {
  347. dt.Columns.Add(headerRow.GetCell(i).ToString());
  348. }
  349. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  350. {
  351. DataRow dr = dt.NewRow();
  352. IRow row = sheet.GetRow(i);
  353. for (int j = row.FirstCellNum; j < cellCount; j++)
  354. {
  355. if (row.GetCell(j) != null)
  356. {
  357. dr[j] = row.GetCell(j).ToString();
  358. }
  359. }
  360. dt.Rows.Add(dr);
  361. }
  362. sheet = null;
  363. workbook = null;
  364. return dt;
  365. }
  366. }
  367. }