ExcelReader.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using NPOI.SS.UserModel;
  2. using NPOI.XSSF.UserModel;
  3. namespace Universal;
  4. public class ExcelReader
  5. {
  6. public static Dictionary<string, Dictionary<int, Dictionary<int, string>>> Read(string filePath, int startRow)
  7. {
  8. Dictionary<string, Dictionary<int, Dictionary<int, string>>> sheets = [];
  9. using FileStream file = new(filePath, FileMode.Open, FileAccess.Read);
  10. for (int i = 0; ; i++)
  11. {
  12. ISheet sheet;
  13. try
  14. {
  15. sheet = new XSSFWorkbook(file).GetSheetAt(i);
  16. if (sheet is null)
  17. break;
  18. }
  19. catch
  20. {
  21. break;
  22. }
  23. Dictionary<int, Dictionary<int, string>> contents = [];
  24. sheets[sheet.SheetName] = contents;
  25. for (int row = startRow; row <= sheet.LastRowNum; row++)
  26. {
  27. if (sheet.GetRow(row) is not IRow currentRow)
  28. continue;
  29. contents[row] = [];
  30. for (int colum = 0; colum < currentRow.LastCellNum; colum++)
  31. {
  32. ICell cell = currentRow.GetCell(colum);
  33. contents[row][colum] = cell?.ToString() ?? string.Empty;
  34. }
  35. }
  36. }
  37. return sheets;
  38. }
  39. }