ExcelUtil.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.IO;
  5. using System.Linq;
  6. using NPOI.HSSF.UserModel;
  7. using NPOI.SS.UserModel;
  8. using NPOI.XSSF.UserModel;
  9. namespace Team.Utility
  10. {
  11. /// <summary>
  12. /// poi类库实现的excel工具类
  13. /// excel文件到table,table到excel
  14. /// </summary>
  15. public static class ExcelUtil
  16. {
  17. /// <summary>
  18. /// Excel导入成Datable
  19. /// </summary>
  20. /// <param name="file">导入路径(包含文件名与扩展名)</param>
  21. /// <param name="isFirstRowAsHeader"></param>
  22. /// <returns>
  23. /// </returns>
  24. /// Exception("无效的文件扩展名"),要求xls,xlsx格式
  25. public static DataTable ExcelToTable(string file,bool isFirstRowAsHeader=true)
  26. {
  27. var dt = new DataTable();
  28. var fileExt = Path.GetExtension(file)?.ToLower();
  29. using var fs = new FileStream(file, FileMode.Open, FileAccess.Read,FileShare.ReadWrite);
  30. //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
  31. IWorkbook workbook = fileExt switch
  32. {
  33. ".xlsx" => new XSSFWorkbook(fs),
  34. ".xls" => new HSSFWorkbook(fs),
  35. _ => throw new Exception("无效的文件扩展名")
  36. };
  37. var sheet = workbook.GetSheetAt(0);
  38. var columns = new List<int>();
  39. //表头
  40. var header = sheet.GetRow(sheet.FirstRowNum);
  41. for (var i = 0; i < header.LastCellNum; i++)
  42. {
  43. var obj = GetValueType(header.GetCell(i));
  44. if (obj == null || obj.ToString() == string.Empty||!isFirstRowAsHeader)
  45. dt.Columns.Add(new DataColumn("Columns" + i));
  46. else
  47. dt.Columns.Add(new DataColumn(obj.ToString()));
  48. columns.Add(i);
  49. }
  50. var firstRow = isFirstRowAsHeader ? sheet.FirstRowNum + 1 : sheet.FirstRowNum;
  51. //数据
  52. for (var i = firstRow; i <= sheet.LastRowNum; i++)
  53. {
  54. var dr = dt.NewRow();
  55. var hasValue = false;
  56. foreach (var j in columns)
  57. {
  58. dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
  59. if (dr[j] != null && dr[j].ToString() != string.Empty)
  60. {
  61. hasValue = true;
  62. }
  63. }
  64. if (hasValue)
  65. {
  66. dt.Rows.Add(dr);
  67. }
  68. }
  69. return dt;
  70. }
  71. /// <summary>
  72. /// Datable导出成Excel
  73. /// </summary>
  74. /// <param name="dt"></param>
  75. /// <param name="file">导出路径(包括文件名与扩展名)</param>
  76. /// <param name="isAddHeader">默认添加表头</param>
  77. /// Exception("无效的文件扩展名"),要求xls,xlsx格式
  78. public static void TableToExcel(DataTable dt, string file,bool isAddHeader=true)
  79. {
  80. var fileExt = Path.GetExtension(file)?.ToLower();
  81. IWorkbook workbook = fileExt switch
  82. {
  83. ".xlsx" => new XSSFWorkbook(),
  84. ".xls" => new HSSFWorkbook(),
  85. _ => throw new Exception("无效的文件扩展名")
  86. };
  87. var sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);//sheet名
  88. if (isAddHeader)
  89. {
  90. var row = sheet.CreateRow(0);
  91. for (var i = 0; i < dt.Columns.Count; i++)
  92. {
  93. var cell = row.CreateCell(i);
  94. cell.SetCellValue(dt.Columns[i].ColumnName);
  95. }
  96. //数据
  97. }
  98. for (var i = 0; i < dt.Rows.Count; i++)
  99. {
  100. var row1 = sheet.CreateRow(i + 1);
  101. for (var j = 0; j < dt.Columns.Count; j++)
  102. {
  103. var cell = row1.CreateCell(j);
  104. cell.SetCellValue(dt.Rows[i][j].ToString());
  105. }
  106. }
  107. //表头
  108. //转为字节数组
  109. using var stream = new MemoryStream();
  110. workbook.Write(stream);
  111. var buf = stream.ToArray();
  112. //保存为Excel文件
  113. using var fs = new FileStream(file, FileMode.Create, FileAccess.Write);
  114. fs.Write(buf, 0, buf.Length);
  115. fs.Flush();
  116. }
  117. public static IRow ExtensionMethod(ISheet sheet,int rowIndex)
  118. {
  119. var row= sheet.CreateRow(rowIndex);
  120. return row;
  121. }
  122. public static void TableToExcel(DataTable []dts, string file)
  123. {
  124. IWorkbook workbook;
  125. var fileExt = Path.GetExtension(file)?.ToLower();
  126. if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; }
  127. if (workbook == null) { return; }
  128. foreach (var dt in dts)
  129. {
  130. var sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet($"Sheet{dts.ToList().IndexOf(dt)}") : workbook.CreateSheet(dt.TableName);
  131. //表头
  132. var row = sheet.CreateRow(0);
  133. for (var i = 0; i < dt.Columns.Count; i++)
  134. {
  135. var cell = row.CreateCell(i);
  136. cell.SetCellValue(dt.Columns[i].ColumnName);
  137. }
  138. //数据
  139. for (var i = 0; i < dt.Rows.Count; i++)
  140. {
  141. var row1 = sheet.CreateRow(i + 1);
  142. for (var j = 0; j < dt.Columns.Count; j++)
  143. {
  144. var cell = row1.CreateCell(j);
  145. cell.SetCellValue(dt.Rows[i][j].ToString());
  146. }
  147. }
  148. }
  149. //转为字节数组
  150. var stream = new MemoryStream();
  151. workbook.Write(stream);
  152. var buf = stream.ToArray();
  153. //保存为Excel文件
  154. using (var fs = new FileStream(file, FileMode.Create, FileAccess.Write))
  155. {
  156. fs.Write(buf, 0, buf.Length);
  157. fs.Flush();
  158. }
  159. }
  160. /// <summary>
  161. /// 获取单元格类型
  162. /// </summary>
  163. /// <param name="cell"></param>
  164. /// <returns></returns>
  165. private static object GetValueType(ICell cell)
  166. {
  167. if (cell == null)
  168. return null;
  169. switch (cell.CellType)
  170. {
  171. case CellType.Blank: //BLANK:
  172. return null;
  173. case CellType.Boolean: //BOOLEAN:
  174. return cell.BooleanCellValue;
  175. case CellType.Numeric: //NUMERIC:
  176. return cell.NumericCellValue;
  177. case CellType.String: //STRING:
  178. return cell.StringCellValue;
  179. case CellType.Error: //ERROR:
  180. return cell.ErrorCellValue;
  181. default:
  182. return "=" + cell.CellFormula;
  183. }
  184. }
  185. }
  186. }