[英]NPOI - Get excel row count to check if it is empty
我正在使用NPOI
lib和C#
讀取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行以便正確處理問題並顯示消息
如果我針對只有1行(標題)的excel文件運行我的代碼,它會中斷
cell.SetCellType(CellType.String); //--- here cell is null
出現以下錯誤:
Object reference not set to an instance of an object.
我也試着用行計數
sheet.LastRowNum
但它沒有返回正確的行數。 例如,我創建了一個包含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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.