我有一个巨大的 excel 文件,其中包含大量列,如下所示:-
Column1 Column2 Column3 Column4 Column5
abc def ghi
mno pqr
......
这是我为打印这些值而编写的代码:
try {
FileInputStream inputStr = new FileInputStream(fileName);
XSSFWorkbook xssfWork = new XSSFWorkbook(inputStr) ;
XSSFSheet sheet1 = xssfWork.getSheetAt(0);
Iterator rowItr = sheet1.rowIterator();
while ( rowItr.hasNext() ) {
XSSFRow row = (XSSFRow) rowItr.next();
System.out.println("ROW:-->");
Iterator cellItr = row.cellIterator();
while ( cellItr.hasNext() ) {
XSSFCell cell = (XSSFCell) cellItr.next();
System.out.println("CELL:-->"+cell.toString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
这段代码生成的输出是:-
ROW:-->
CELL:-->Column1
CELL:-->Column2
CELL:-->Column3
CELL:-->Column4
CELL:-->Column5
ROW:-->
CELL:-->abc
CELL:-->def
CELL:-->ghi
ROW:-->
CELL:-->mno
CELL:-->pqr
所以,如果我们查看上面的输出,我们可以注意到我留下空白值的单元格没有被 POI 库拾取,有没有办法可以将这些值设为 null。还是一种识别所显示的值跳过空白单元格的方法?
谢谢。
最佳答案
如果您想获取所有单元格,无论它们是否存在,那么迭代器都不适合您。相反,您需要手动获取适当的单元格,可能缺少单元格策略
for(Row row : sheet) {
for(int cn=0; cn<row.getLastCellNum(); cn++) {
// If the cell is missing from the file, generate a blank one
// (Works by specifying a MissingCellPolicy)
Cell cell = row.getCell(cn, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
// Print the cell for debugging
System.out.println("CELL: " + cn + " --> " + cell.toString());
}
}
在 the Apache POI documentation on iterating over cells 中有更多详细信息。
关于java - 如何在 Apache POI 中获取 Excel 空白单元格值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4929646/