2015-07-10 1582 views
3

我在使用NPOI lib和C#讀取xlsx文件。我需要提取一些excel列並將提取的值保存到某種數據結構中。NPOI - 獲取excel行數以檢查它是否爲空

我可以成功讀取該文件,並從第2獲得的所有值(第一個只包含頭)到最後一行用下面的代碼:

... 
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的只有1行文件(頭)顯示一條消息

,它打破

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文件中的代碼。​​總是返回4作爲結果,而不是1 ....我認爲這涉及到一些屬性綁定到手動清理表單元格。

你有什麼提示來解決這個問題嗎?

回答

2

我認爲這將是明智的使用sheet.LastRowNum應返回當前工作表

+1

請看我的問題,我已經嘗試過,但它沒有按預期工作。 – BeNdErR

+0

這是因爲理論上這些單元格仍然存在於Excel中,但是作爲元數據附加到這些單元格的空單元取決於您如何刪除這些單元格的內容。這對於excel文檔,特別是對於非技術用戶來說總是一個問題。如果這些單元格中的數據有效,則必須爲自己的案例測試添加自定義驗證 – McLoving

2

我是不是簡單化的行的金額是多少?

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; 
     } 
+0

只需記住在繼續之前增加rowIndex; –

0

您可以檢索使用此代碼的行數:

public int GetTotalRowCount(bool warrant = false) 
{ 
    IRow headerRow = activeSheet.GetRow(0); 
    if (headerRow != null) 
    { 
     int rowCount = activeSheet.LastRowNum + 1; 
     return rowCount; 
    } 
    return 0; 
} 
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; 
    }