2017-10-08 183 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 
     } 
    } 
} 
相关问题