NPOIExcle.cs 14 KB

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