在我的代码中,我逐行检查一个 XLSX 文件,并使用 Apache POI 4.1.0 对数据库进行验证。如果我发现不正确的行,我会通过将其添加到List<XSSFRow> toRemove. 在遍历每一行之后,这个小方法应该删除标记为删除的行:
ListIterator<XSSFRow> rowIterator = toRemove.listIterator(toRemove.size());
while (rowIterator.hasPrevious()) {
XSSFRow row = rowIterator.previous();
if (row != null && row.getSheet() == sheet) {
int lastRowNum = sheet.getLastRowNum();
int rowIndex = row.getRowNum();
if (rowIndex == lastRowNum) {
sheet.removeRow(row);
} else if (rowIndex >= 0 && rowIndex < lastRowNum) {
sheet.removeRow(row);
} else {
System.out.println("\u001B[31mERROR: Removal failed because row " + rowIndex + " is out of bounds\u001B[0m");
}
System.out.println("Row " + rowIndex + " successfully removed");
} else {
System.out.println("Row skipped in removal because it was null already");
}
}
getRowNum()但由于某些未知原因,它完美地删除了所有行,然后在获取最后(第一个添加的)行的行索引 ( ) 时抛出 XmlValueDisconnectedException 。
Stacktrace的相关部分:
org.apache.xmlbeans.impl.values.XmlValueDisconnectedException
at org.apache.xmlbeans.impl.values.XmlObjectBase.check_orphaned(XmlObjectBase.java:1258)
at org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTRowImpl.getR(Unknown Source)
at org.apache.poi.xssf.usermodel.XSSFRow.getRowNum(XSSFRow.java:400)
at Overview.removeRows(Overview.java:122)
编辑:我也尝试更改迭代过程(见下文)但错误保持不变。
for (XSSFRow row : toRemove) {
// same code as above without iterator and while
}
偶然的你
相关分类