Apache POI跳过从未更新过的行。

3
在使用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行(行号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
1个回答

1
这是完全符合预期的,就如文档中所解释的一样!
迭代器的作用是为了方便获取包含内容的行和单元格(以及 Excel 文件中其他随机包含的元素…)。
如果您想获取每行每个单元格的内容,无论它们是否被定义,那么您需要按行和列号进行循环,请参考文档中的建议,例如:
// 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
      }
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接