I am trying to print a string in a specific column of a xlsx file using apache poi in java. I have parsed the column x using regex and printing the required string in column y. However the getRowNum() of the code flags ConcurrentModificationExceptio. Below is the code snippet. Please help
|Column X|Column Y|
|Barath |Bar | //Regex Matches Bar and prints it in Column y (Required output).
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
Matcher m = p.matcher(cell.getRichStringCellValue().getString());
//rownr = row.getRowNum();
if(m.find()){
sheet.createRow(row.getRowNum()).createCell(colnr+6).setCellValue(row.getCell(colnr+4).toString().substring(m.start(),m.end()-1).replace(":", "")); //row.getRowNum() function causes Concurrent modification exception colnr+6 is destination column and Colnr+4 is column to be parsed.
System.out.print(row.getCell(colnr+4).toString().substring(m.start(),m.end()-1).replace(":", "")+"\n"); //Prints the parsed string in the console correctly
}
}
}
}
It seems that, when you are creating a row, the original rows
collection is modified, while you are iterating over it. Hence the ConcurrentModificationException
.
There are a few ways to fix this, but in this case, I don't think you need to create the row at all, since the row already exists. So instead of...
sheet.createRow(...).createCell(colnr+6)
...you would have:
row.createCell(colnr+6)