[英]Java ConcurrentModificationException Error while writing in Excel
[英]Error when editing an excel file with Java (ConcurrentModificationException)
我正在嘗試修改 excel 工作簿中的最后一個單元格,該工作簿在任何單元格中都匹配另一個值。
在第一次迭代中它工作正常,但在第二個循環中,我在 for ( java.util.ConcurrentModificationException
for (Cell cell: row) {
line.
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1486)
at java.base/java.util.TreeMap$ValueIterator.next(TreeMap.java:1531)
at Package.Fotos.initial(Fotos.java:266)
at Package.Fotos.main(Fotos.java:360)
有誰知道我做錯了什么? 這是我根據這個答案使用的代碼。
...
for (int i = 0; i < cuentafilas; i++) {
List<WebElement> columnas = filas.get(i).findElements(By.tagName("img"));
int cuentacolumnas = columnas.size();
for (int k = 0; k < cuentacolumnas; k++) {
String c = columnas.get(k).getAttribute("src");
if (c.contains("jpg")) {
String filtroValor = id;
Workbook libro = WorkbookFactory.create(new FileInputStream("D:\\archivos\\entrada.xlsx"));
DataFormatter formatter = new DataFormatter();
Sheet hoja = libro.getSheetAt(0);
for (Row row : hoja) {
for (Cell cell : row) {
CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
String text = formatter.formatCellValue(cell);
if (filtroValor.equals(text)) {
Row fila = hoja.getRow(row.getRowNum());
int ultimaCelda = fila.getLastCellNum();
Cell celda = fila.createCell(ultimaCelda);
celda.setCellValue(c);
OutputStream os = new FileOutputStream("D:\\archivos\\entrada.xlsx");
libro.write(os);
}
}
}
}
}
}
...
謝謝。
錯誤在於
Cell celda = fila.createCell(ultimaCelda);
在該行中創建一個新單元格。 在遍歷所有單元格的列表時,您不能添加單元格。 嘗試創建您要編輯的列表的副本並迭代該列表,以便另一個變得可編輯
java.util.ConcurrentModificationException
在編輯列表時出現,您當前正在迭代。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.