NPOIExcle.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. using NPOI.HSSF.UserModel;
  2. using NPOI.SS.UserModel;
  3. using NPOI.XSSF.UserModel;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace wispro.sp.utility
  12. {
  13. public class NPOIExcel
  14. {
  15. /// <summary>
  16. /// 将excel导入到datatable
  17. /// </summary>
  18. /// <param name="filePath">excel路径</param>
  19. /// <param name="isColumnName">是否有列名</param>
  20. /// <param name="ColumnNameRow">列名的所在行,0为第一行</param>
  21. /// <param name="IgnoreZeroHightRow">是否忽略隐藏行</param>
  22. /// <returns>返回datatable</returns>
  23. public static DataTable ExcelToDataTable(string filePath, bool isColumnName,bool IgnoreZeroHightRow = false,int ColumnNameRow=0)
  24. {
  25. DataTable dataTable = null;
  26. FileStream fs = null;
  27. DataColumn column = null;
  28. DataRow dataRow = null;
  29. IWorkbook workbook = null;
  30. ISheet sheet = null;
  31. IRow row = null;
  32. ICell cell = null;
  33. int startRow = 0;
  34. try
  35. {
  36. using (fs = File.OpenRead(filePath))
  37. {
  38. // 2007版本
  39. if (filePath.IndexOf(".xlsx") > 0)
  40. workbook = new XSSFWorkbook(fs);
  41. // 2003版本
  42. else if (filePath.IndexOf(".xls") > 0)
  43. workbook = new HSSFWorkbook(fs);
  44. if (workbook != null)
  45. {
  46. sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet
  47. dataTable = new DataTable();
  48. if (sheet != null)
  49. {
  50. int rowCount = sheet.LastRowNum;//总行数
  51. if (rowCount > 0)
  52. {
  53. IRow firstRow = sheet.GetRow(ColumnNameRow);//列头行
  54. int cellCount = firstRow.LastCellNum;//列数
  55. //构建datatable的列
  56. if (isColumnName)
  57. {
  58. startRow = ColumnNameRow+1;//如果有列名,则从第列头行的下一行开始读取
  59. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  60. {
  61. cell = firstRow.GetCell(i);
  62. if (cell != null)
  63. {
  64. if (cell.StringCellValue != null)
  65. {
  66. column = new DataColumn(cell.StringCellValue);
  67. dataTable.Columns.Add(column);
  68. }
  69. }
  70. }
  71. }
  72. else
  73. {
  74. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  75. {
  76. column = new DataColumn("column" + (i + 1));
  77. dataTable.Columns.Add(column);
  78. }
  79. }
  80. //填充行
  81. for (int i = startRow; i <= rowCount; ++i)
  82. {
  83. row = sheet.GetRow(i);
  84. if (row != null && IgnoreZeroHightRow && row.ZeroHeight)
  85. {
  86. System.Diagnostics.Debug.WriteLine (string.Format("[{0}]隐藏行:{1}", filePath, i));
  87. continue;
  88. }
  89. if (row == null || row.Cells.Count ==0) continue;
  90. dataRow = dataTable.NewRow();
  91. for (int j = row.FirstCellNum; j < cellCount; ++j)
  92. {
  93. cell = row.GetCell(j);
  94. if (cell == null)
  95. {
  96. dataRow[j] = "";
  97. }
  98. else
  99. {
  100. //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
  101. switch (cell.CellType)
  102. {
  103. case CellType.Blank:
  104. dataRow[j] = "";
  105. break;
  106. case CellType.Numeric:
  107. short format = cell.CellStyle.DataFormat;
  108. //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
  109. if (DateUtil.IsCellDateFormatted(cell))// || format == 14 || format == 31 || format == 57 || format == 58 || format == 165 || format == 177 || format == 176)
  110. try
  111. {
  112. dataRow[j] = cell.DateCellValue;
  113. }
  114. catch
  115. {
  116. //dataRow[j] = null;
  117. }
  118. else
  119. dataRow[j] = cell.NumericCellValue;
  120. break;
  121. case CellType.String:
  122. dataRow[j] = cell.StringCellValue;
  123. break;
  124. }
  125. }
  126. }
  127. dataTable.Rows.Add(dataRow);
  128. }
  129. }
  130. }
  131. }
  132. }
  133. return dataTable;
  134. }
  135. catch (Exception ex)
  136. {
  137. if (fs != null)
  138. {
  139. fs.Close();
  140. }
  141. return null;
  142. }
  143. }
  144. public static DataTable ExcelToDataTable(string v)
  145. {
  146. return ExcelToDataTable(v, false, true);
  147. }
  148. /// <summary>
  149. /// 写入excel
  150. /// </summary>
  151. /// <param name="dt">datatable</param>
  152. /// <param name="strFile">strFile</param>
  153. /// <returns></returns>
  154. public static bool DataTableToExcel(DataTable dt, string strFile)
  155. {
  156. bool result = false;
  157. IWorkbook workbook = null;
  158. FileStream fs = null;
  159. IRow row = null;
  160. ISheet sheet = null;
  161. ICell cell = null;
  162. try
  163. {
  164. if (dt != null && dt.Rows.Count > 0)
  165. {
  166. workbook = new XSSFWorkbook();
  167. sheet = workbook.CreateSheet("Sheet0");//创建一个名称为Sheet0的表
  168. int rowCount = dt.Rows.Count;//行数
  169. int columnCount = dt.Columns.Count;//列数
  170. //设置列头
  171. row = sheet.CreateRow(0);//excel第一行设为列头
  172. for (int c = 0; c < columnCount; c++)
  173. {
  174. cell = row.CreateCell(c);
  175. cell.SetCellValue(dt.Columns[c].ColumnName);
  176. }
  177. //设置每行每列的单元格,
  178. for (int i = 0; i < rowCount; i++)
  179. {
  180. row = sheet.CreateRow(i + 1);
  181. for (int j = 0; j < columnCount; j++)
  182. {
  183. cell = row.CreateCell(j);//excel第二行开始写入数据
  184. cell.SetCellValue(dt.Rows[i][j].ToString());
  185. }
  186. }
  187. using (fs = File.OpenWrite(strFile))
  188. {
  189. workbook.Write(fs);//向打开的这个xls文件中写入数据
  190. result = true;
  191. }
  192. }
  193. return result;
  194. }
  195. catch (Exception ex)
  196. {
  197. if (fs != null)
  198. {
  199. fs.Close();
  200. }
  201. return false;
  202. }
  203. }
  204. /// <summary>
  205. /// Excel导入成Datable
  206. /// </summary>
  207. /// <param name="file">导入路径(包含文件名与扩展名)</param>
  208. /// <returns></returns>
  209. public static DataTable ExcelToTable(string file)
  210. {
  211. DataTable dt = new DataTable();
  212. IWorkbook workbook;
  213. string fileExt = Path.GetExtension(file).ToLower();
  214. using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
  215. {
  216. //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
  217. if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
  218. if (workbook == null) { return null; }
  219. ISheet sheet = workbook.GetSheetAt(0);
  220. //表头
  221. IRow header = sheet.GetRow(sheet.FirstRowNum);
  222. List<int> columns = new List<int>();
  223. for (int i = 0; i < header.LastCellNum; i++)
  224. {
  225. object obj = GetValueType(header.GetCell(i));
  226. if (obj == null || obj.ToString() == string.Empty)
  227. {
  228. dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
  229. }
  230. else
  231. dt.Columns.Add(new DataColumn(obj.ToString()));
  232. columns.Add(i);
  233. }
  234. //数据
  235. for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
  236. {
  237. DataRow dr = dt.NewRow();
  238. bool hasValue = false;
  239. foreach (int j in columns)
  240. {
  241. dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
  242. if (dr[j] != null && dr[j].ToString() != string.Empty)
  243. {
  244. hasValue = true;
  245. }
  246. }
  247. if (hasValue)
  248. {
  249. dt.Rows.Add(dr);
  250. }
  251. }
  252. }
  253. return dt;
  254. }
  255. /// <summary>
  256. /// Datable导出成Excel
  257. /// </summary>
  258. /// <param name="dt"></param>
  259. /// <param name="file">导出路径(包括文件名与扩展名)</param>
  260. public static void TableToExcel(DataTable dt, string file)
  261. {
  262. IWorkbook workbook;
  263. string fileExt = Path.GetExtension(file).ToLower();
  264. if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; }
  265. if (workbook == null) { return; }
  266. ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);
  267. //表头
  268. IRow row = sheet.CreateRow(0);
  269. for (int i = 0; i < dt.Columns.Count; i++)
  270. {
  271. ICell cell = row.CreateCell(i);
  272. cell.SetCellValue(dt.Columns[i].ColumnName);
  273. }
  274. //数据
  275. for (int i = 0; i < dt.Rows.Count; i++)
  276. {
  277. IRow row1 = sheet.CreateRow(i + 1);
  278. for (int j = 0; j < dt.Columns.Count; j++)
  279. {
  280. ICell cell = row1.CreateCell(j);
  281. cell.SetCellValue(dt.Rows[i][j].ToString());
  282. }
  283. }
  284. //转为字节数组
  285. MemoryStream stream = new MemoryStream();
  286. workbook.Write(stream);
  287. var buf = stream.ToArray();
  288. //保存为Excel文件
  289. using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
  290. {
  291. fs.Write(buf, 0, buf.Length);
  292. fs.Flush();
  293. }
  294. }
  295. /// <summary>
  296. /// 获取单元格类型
  297. /// </summary>
  298. /// <param name="cell"></param>
  299. /// <returns></returns>
  300. private static object GetValueType(ICell cell)
  301. {
  302. if (cell == null)
  303. return null;
  304. switch (cell.CellType)
  305. {
  306. case CellType.Blank: //BLANK:
  307. return null;
  308. case CellType.Boolean: //BOOLEAN:
  309. return cell.BooleanCellValue;
  310. case CellType.Numeric: //NUMERIC:
  311. return cell.NumericCellValue;
  312. case CellType.String: //STRING:
  313. return cell.StringCellValue;
  314. case CellType.Error: //ERROR:
  315. return cell.ErrorCellValue;
  316. case CellType.Formula: //FORMULA:
  317. default:
  318. return "=" + cell.CellFormula;
  319. }
  320. }
  321. }
  322. }