2017-10-08 58 views
0

這是excel表如果第一個和最後一個單元格的值爲空或空白,如何讀取Excel工作表的每一行的每個單元格的值?

----------------------------------------------------------------------- 
col1 | Col2 | col3 | col4 | col5| col6| col7| and so on 
----------------------------------------------------------------------- 
1 | 2 | 3 | 4 | 5 | 6| 7|  and so on 
------------------------------------------------------------------------ 
    |  | 3 | 4 | 5 | |  |  and so on 
------------------------------------------------------------------------ 

我的輸出應是 空空3 4 5空空

我讀此使用Iterator<Cell>cell=row.cellIterator 欲讀取也空白每個細胞的值的Excel工作表但使用CellIterator我能夠從第二行讀取3 4 5。

如何讀空間的第二行?我也看到如果第一個單元格和最後一個單元格不是空白,那麼CellIterator也成功讀取空白值。

如何讀取java中的特定行的每個單元格值,如果該行的第一個和最後一個單元格是空白的?

回答

0

我將假定您正在使用Apache POI進行Excel操作。

CellIterator將只返回已在文件中定義的單元格,這主要是指具有值或格式的單元格。

參考http://poi.apache.org/spreadsheet/quick-guide.html#Iterate+over+cells%2C+with+control+of+missing+%2F+blank+cells

遍歷細胞,缺少/空白單元格

在某些情況下的控制權,迭代的時候,你需要在如何丟失或空行和細胞治療的完全控制,你需要確保你訪問每個單元格,而不僅僅是文件中定義的單元格。 (CellIterator只會返回文件中定義的單元格,這主要是那些帶有值或樣式的單元格,但它依賴於Excel)。

在這些情況下,您應該獲取行的第一列和最後一列信息,然後調用getCell(int,MissingCellPolicy)來獲取單元格。使用MissingCellPolicy來控制空白或空單元格的處理方式。

// Decide which rows to process 
int rowStart = Math.min(15, sheet.getFirstRowNum()); 
int rowEnd = Math.max(1400, sheet.getLastRowNum()); 

for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) { 
    Row r = sheet.getRow(rowNum); 
    if (r == null) { 
     // This whole row is empty 
     // Handle it as needed 
     continue; 
    } 

    int lastColumn = Math.max(r.getLastCellNum(), MY_MINIMUM_COLUMN_COUNT); 

    for (int cn = 0; cn < lastColumn; cn++) { 
     Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL); 
     if (c == null) { 
     // The spreadsheet is empty in this cell 
     } else { 
     // Do something useful with the cell's contents 
     } 
    } 
} 
相關問題