NPOI – 获取excel行数来检查是否为空

我正在用C#读取一个使用NPOI库的xlsx文件。 我需要提取一些excel列,并将提取的值保存到某种数据结构中。

我可以成功读取文件,并从第二个(第一个只包含标题)到下一个代码的最后一行获取所有值:

 ... workbook = new XSSFWorkbook(fs); sheet = (XSSFSheet)workbook.GetSheetAt(0); .... int rowIndex = 1; //--- SKIP FIRST ROW (index == 0) AS IT CONTAINS TEXT HEADERS while (sheet.GetRow(rowIndex) != null) { for (int i = 0; i < this.columns.Count; i++){ int colIndex = this.columns[i].colIndex; ICell cell = sheet.GetRow(rowIndex).GetCell(colIndex); cell.SetCellType(CellType.String); String cellValue = cell.StringCellValue; this.columns[i].values.Add(cellValue); //--- Here I'm adding the value to a custom data structure } rowIndex++; } 

我现在想要做的是检查如果Excel文件是空的,或者如果它只有1行,以正确处理问题,并显示一条消息

如果我只用一行(头文件)对excel文件运行我的代码,它会中断

 cell.SetCellType(CellType.String); //--- here cell is null 

出现以下错误:

 Object reference not set to an instance of an object. 

我也试图得到行数

 sheet.LastRowNum 

但它不会返回正确的行数。 例如,我创build了5行(1xHEADER + 4xDATA)的Excel,代码读取成功的Excel值。 在同一个Excel中,我已经删除了4个数据行,然后再次启动了Excel文件中的代码。 sheet.LastRowNum保持返回4结果,而不是1 ….我认为这是一些属性绑定到手动清理表单元格。

你有什么提示来解决这个问题吗?

我认为这是明智的使用sheet.LastRowNum应该返回当前表中的行数

我简单化了吗?

  bool hasContent = false; while (sheet.GetRow(rowIndex) != null) { var row = rows.Current as XSSFRow; //all cells are empty, so is a 'blank row' if (row.Cells.All(d => d.CellType == CellType.Blank)) continue; hasContent = true; } 

您可以使用此代码检索行数:

 public int GetTotalRowCount(bool warrant = false) { IRow headerRow = activeSheet.GetRow(0); if (headerRow != null) { int rowCount = activeSheet.LastRowNum + 1; return rowCount; } return 0; } 

以下是获取实际最后一行索引和物理现有行数的方法:

  public static int LastRowIndex(this ISheet aExcelSheet) { IEnumerator rowIter = aExcelSheet.GetRowEnumerator(); return rowIter.MoveNext() ? aExcelSheet.LastRowNum : -1; } public static int RowsSpanCount(this ISheet aExcelSheet) { return aExcelSheet.LastRowIndex() + 1; } public static int PhysicalRowsCount(this ISheet aExcelSheet ) { if (aExcelSheet == null) { return 0; } int rowsCount = 0; IEnumerator rowEnumerator = aExcelSheet.GetRowEnumerator(); while (rowEnumerator.MoveNext()) { ++rowsCount; } return rowsCount; }