Error when editing an excel file with Java (ConcurrentModificationException)

127 Views Asked by At

I'm trying to modify the last cell of the rows in an excel workbook that in any cell match another value.

In the first iteration it works fine, but in the second loop I get this java.util.ConcurrentModificationException error in the 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)

Does anyone know what I'm doing wrong? This is the code I'm using based on this answer.

...
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);
          }
        }
      }
    }
  }
}
...

Thanks.

1

There are 1 best solutions below

1
On

The error lies in

Cell celda = fila.createCell(ultimaCelda);

where you create a new cell in the row. You can't add a cell, while iterating over the list of all cells. Try creating a copy of the list you are wanting to edit and iterate over that one instead, so the other one becomes editable

the java.util.ConcurrentModificationException appears, when editing a list, that you are currently iterating over.