在使用Apache POI处理Excel文件时,我发现它会跳过某些空行。经过多次尝试和错误,我发现Apache POI只会读取那些单元格被更新过的行。
我编写了一个简短的程序来读取XLSX(XSSF模型)文件中的空行。这是我的输入Excel文件:
我编写了一个简短的程序来读取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行(行号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