NPOIExcle.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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.GetCell(1).ToString()== "PACN2110126")
  85. {
  86. System.Diagnostics.Debug.WriteLine("");
  87. }
  88. if (row != null && IgnoreZeroHightRow && row.ZeroHeight)
  89. {
  90. System.Diagnostics.Debug.WriteLine (string.Format("[{0}]隐藏行:{1}", filePath, i));
  91. continue;
  92. }
  93. if (row == null || row.Cells.Count ==0) continue;
  94. dataRow = dataTable.NewRow();
  95. for (int j = row.FirstCellNum; j < cellCount; ++j)
  96. {
  97. cell = row.GetCell(j);
  98. if (cell == null)
  99. {
  100. dataRow[j] = "";
  101. }
  102. else
  103. {
  104. //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
  105. switch (cell.CellType)
  106. {
  107. case CellType.Blank:
  108. dataRow[j] = "";
  109. break;
  110. case CellType.Numeric:
  111. short format = cell.CellStyle.DataFormat;
  112. //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
  113. if (DateUtil.IsCellDateFormatted(cell))// || format == 14 || format == 31 || format == 57 || format == 58 || format == 165 || format == 177 || format == 176)
  114. try
  115. {
  116. dataRow[j] = cell.DateCellValue;
  117. }
  118. catch
  119. {
  120. //dataRow[j] = null;
  121. }
  122. else
  123. dataRow[j] = cell.NumericCellValue;
  124. break;
  125. case CellType.String:
  126. dataRow[j] = cell.StringCellValue;
  127. break;
  128. }
  129. }
  130. }
  131. dataTable.Rows.Add(dataRow);
  132. }
  133. }
  134. }
  135. }
  136. }
  137. return dataTable;
  138. }
  139. catch (Exception ex)
  140. {
  141. if (fs != null)
  142. {
  143. fs.Close();
  144. }
  145. return null;
  146. }
  147. }
  148. public static DataTable ExcelToDataTable(string v)
  149. {
  150. return ExcelToDataTable(v, false, true);
  151. }
  152. /// <summary>
  153. /// 写入excel
  154. /// </summary>
  155. /// <param name="dt">datatable</param>
  156. /// <param name="strFile">strFile</param>
  157. /// <returns></returns>
  158. public static bool DataTableToExcel(DataTable dt, string strFile)
  159. {
  160. bool result = false;
  161. IWorkbook workbook = null;
  162. FileStream fs = null;
  163. IRow row = null;
  164. ISheet sheet = null;
  165. ICell cell = null;
  166. try
  167. {
  168. if (dt != null && dt.Rows.Count > 0)
  169. {
  170. workbook = new XSSFWorkbook();
  171. sheet = workbook.CreateSheet("Sheet0");//创建一个名称为Sheet0的表
  172. int rowCount = dt.Rows.Count;//行数
  173. int columnCount = dt.Columns.Count;//列数
  174. //设置列头
  175. row = sheet.CreateRow(0);//excel第一行设为列头
  176. for (int c = 0; c < columnCount; c++)
  177. {
  178. cell = row.CreateCell(c);
  179. cell.SetCellValue(dt.Columns[c].ColumnName);
  180. }
  181. //设置每行每列的单元格,
  182. for (int i = 0; i < rowCount; i++)
  183. {
  184. row = sheet.CreateRow(i + 1);
  185. for (int j = 0; j < columnCount; j++)
  186. {
  187. cell = row.CreateCell(j);//excel第二行开始写入数据
  188. cell.SetCellValue(dt.Rows[i][j].ToString());
  189. }
  190. }
  191. using (fs = File.OpenWrite(strFile))
  192. {
  193. workbook.Write(fs);//向打开的这个xls文件中写入数据
  194. result = true;
  195. }
  196. }
  197. return result;
  198. }
  199. catch (Exception ex)
  200. {
  201. if (fs != null)
  202. {
  203. fs.Close();
  204. }
  205. return false;
  206. }
  207. }
  208. /// <summary>
  209. /// Excel导入成Datable
  210. /// </summary>
  211. /// <param name="file">导入路径(包含文件名与扩展名)</param>
  212. /// <returns></returns>
  213. public static DataTable ExcelToTable(string file)
  214. {
  215. DataTable dt = new DataTable();
  216. IWorkbook workbook;
  217. string fileExt = Path.GetExtension(file).ToLower();
  218. using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
  219. {
  220. //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
  221. if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
  222. if (workbook == null) { return null; }
  223. ISheet sheet = workbook.GetSheetAt(0);
  224. //表头
  225. IRow header = sheet.GetRow(sheet.FirstRowNum);
  226. List<int> columns = new List<int>();
  227. for (int i = 0; i < header.LastCellNum; i++)
  228. {
  229. object obj = GetValueType(header.GetCell(i));
  230. if (obj == null || obj.ToString() == string.Empty)
  231. {
  232. dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
  233. }
  234. else
  235. dt.Columns.Add(new DataColumn(obj.ToString()));
  236. columns.Add(i);
  237. }
  238. //数据
  239. for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
  240. {
  241. DataRow dr = dt.NewRow();
  242. bool hasValue = false;
  243. foreach (int j in columns)
  244. {
  245. dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
  246. if (dr[j] != null && dr[j].ToString() != string.Empty)
  247. {
  248. hasValue = true;
  249. }
  250. }
  251. if (hasValue)
  252. {
  253. dt.Rows.Add(dr);
  254. }
  255. }
  256. }
  257. return dt;
  258. }
  259. /// <summary>
  260. /// Datable导出成Excel
  261. /// </summary>
  262. /// <param name="dt"></param>
  263. /// <param name="file">导出路径(包括文件名与扩展名)</param>
  264. public static void TableToExcel(DataTable dt, string file)
  265. {
  266. IWorkbook workbook;
  267. string fileExt = Path.GetExtension(file).ToLower();
  268. if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; }
  269. if (workbook == null) { return; }
  270. ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);
  271. //表头
  272. IRow row = sheet.CreateRow(0);
  273. for (int i = 0; i < dt.Columns.Count; i++)
  274. {
  275. ICell cell = row.CreateCell(i);
  276. cell.SetCellValue(dt.Columns[i].ColumnName);
  277. }
  278. //数据
  279. for (int i = 0; i < dt.Rows.Count; i++)
  280. {
  281. IRow row1 = sheet.CreateRow(i + 1);
  282. for (int j = 0; j < dt.Columns.Count; j++)
  283. {
  284. ICell cell = row1.CreateCell(j);
  285. cell.SetCellValue(dt.Rows[i][j].ToString());
  286. }
  287. }
  288. //转为字节数组
  289. MemoryStream stream = new MemoryStream();
  290. workbook.Write(stream);
  291. var buf = stream.ToArray();
  292. //保存为Excel文件
  293. using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
  294. {
  295. fs.Write(buf, 0, buf.Length);
  296. fs.Flush();
  297. }
  298. }
  299. /// <summary>
  300. /// 获取单元格类型
  301. /// </summary>
  302. /// <param name="cell"></param>
  303. /// <returns></returns>
  304. private static object GetValueType(ICell cell)
  305. {
  306. if (cell == null)
  307. return null;
  308. switch (cell.CellType)
  309. {
  310. case CellType.Blank: //BLANK:
  311. return null;
  312. case CellType.Boolean: //BOOLEAN:
  313. return cell.BooleanCellValue;
  314. case CellType.Numeric: //NUMERIC:
  315. return cell.NumericCellValue;
  316. case CellType.String: //STRING:
  317. return cell.StringCellValue;
  318. case CellType.Error: //ERROR:
  319. return cell.ErrorCellValue;
  320. case CellType.Formula: //FORMULA:
  321. default:
  322. return "=" + cell.CellFormula;
  323. }
  324. }
  325. }
  326. }