在 Apache POI 中处理 excel 文件时,我注意到它会跳过某些空行集。经过大量试验和错误后,我注意到 Apache POI 只会读取那些单元格曾经更新过的行。
我编写了一个简短的程序来读取 XLSX(XSSF 模型)文件中的一行是否为空。这是我输入的 excel 文件:
private static boolean isRowEmpty(Row row) {
boolean isRowEmpty = true;
if (row != null) {
for (Cell cell : row) {
if (cell != null) {
System.out.println("Row:" + cell.getRowIndex() + " Col:"
+ cell.getColumnIndex() + " Len:"
+ cell.toString().length());
isRowEmpty = false;
} else {
System.out.println("Cell is Null at Row "+row.getRowNum());
}
}
} else {
System.out.println("Row is Null");
}
return isRowEmpty;
}
for (Row row : sheet) {
if (isRowEmpty(row)) {
System.out.println("Empty row at " + row.getRowNum());
}
}
输出
Row:0 Col:0 Len:1
Row:2 Col:0 Len:1
Row:3 Col:0 Len:1
Row:4 Col:0 Len:1
Row:5 Col:0 Len:1
Row:6 Col:1 Len:1
Row:7 Col:0 Len:1
Row:8 Col:2 Len:1
在 A5
单元格中,我输入了一个空格,它被 Apache POI 检测到。从输出中可以看出,它不处理第 2 行(rownum 1)。
是否有任何解决方法可以提供以下输出:
Row:0 Col:0 Len:1
Empty Row at 1
Row:2 Col:0 Len:1
Row:3 Col:0 Len:1
Empty Row at 4
Row:5 Col:0 Len:1
Row:6 Col:1 Len:1
Row:7 Col:0 Len:1
Row:8 Col:2 Len:1
谢谢!
更新 1
使用 (cell != null && StringUtils.isNotBlank(cell.toString()))
而不是 (cell != null)
给我以下输出:
Row:0 Col:0 Len:1
Row:2 Col:0 Len:1
Row:3 Col:0 Len:1
Cell is Null for Row 4
Empty row at 4
Row:5 Col:0 Len:1
Row:6 Col:1 Len:1
Row:7 Col:0 Len:1
Row:8 Col:2 Len:1
最佳答案
这完全符合预期,因为 explained in the documentation !
迭代器的作用是让抓取包含内容的行和单元格变得容易(加上 Excel 随机包含在文件中的其他一些...)。
如果你想获取每一行和单元格,不管它们是否被定义,那么你需要遵循 advice in the documentation并按行和单元格编号循环,例如
// 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) {
// Handle there being no cells defined for this row
continue;
}
// Decide how many columns to fetch for this row
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
}
}
}
关于java - Apache POI 跳过从未更新过的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30519539/