NPOIHelper.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using NPOI.HSSF.UserModel;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. //using NPOI.XSSF.UserModel;
  10. using NPOI.SS.UserModel;
  11. using NPOI.SS.Util;
  12. namespace Core.StlMes.Client.PlnSaleOrd
  13. {
  14. public class NPOIHelper
  15. {
  16. /// <summary>读取excel
  17. /// 默认第一行为标头
  18. /// </summary>
  19. /// <param name="strFileName">excel文档路径</param>
  20. /// <returns></returns>
  21. public static DataTable Import(string strFileName)
  22. {
  23. DataTable dt = new DataTable();
  24. HSSFWorkbook hssfworkbook;
  25. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
  26. {
  27. hssfworkbook = new HSSFWorkbook(file);
  28. }
  29. ISheet sheet = hssfworkbook.GetSheetAt(0);
  30. System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
  31. //HSSFRow headerRow = sheet.GetRow(0);
  32. IRow headerRow = sheet.GetRow(0);
  33. int cellCount = headerRow.LastCellNum;
  34. for (int j = 0; j < cellCount; j++)
  35. {
  36. ICell cell = headerRow.GetCell(j);
  37. dt.Columns.Add(cell.ToString());
  38. }
  39. for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
  40. {
  41. IRow row = sheet.GetRow(i);
  42. DataRow dataRow = dt.NewRow();
  43. for (int j = row.FirstCellNum; j < cellCount; j++)
  44. {
  45. if (row.GetCell(j) != null)
  46. dataRow[j] = row.GetCell(j).ToString();
  47. }
  48. dt.Rows.Add(dataRow);
  49. }
  50. return dt;
  51. }
  52. }
  53. }