在迭代行时,需要使用 CellIterator 对象进行迭代而不是使用 row.cellIterator()。这点在 Apache POI 的文档中有说明,应该是因为 row.cellIterator() 会在迭代的过程中可能出现并发错误。以下是一个使用 CellIterator 的示例代码:
// 假设 workbook 和 sheet 已经定义好了
Iterator rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator| cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
System.out.print(cell.getStringCellValue() + "\t");
}
System.out.println();
}
|
注意,在使用 CellIterator 时,你需要显式地设置 row 对象的 Row.MissingCellPolicy 属性。这可以通过以下代码行来完成:
row.setMissingCellPolicy(Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);