1
for(Row row:sheet) {
  for(int rowNo=0;rowNo<sheet.getLastRowNum();rowNo++) {
    row=sheet.getRow(rowNo);
    sheet.removeRow(row);
  }
}

I am trying to remove the rows from Excel file through java but it is giving me error

java.util.ConcurrentModificationException at java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1207) at java.util.TreeMap$ValueIterator.next(TreeMap.java:1252)

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • You look to be looping through the rows twice in the two for loops. Anyhow, it's the implicit iterator in the outer enhanced for loop which is complaining because you are changing the rows in the inner for loop. – Andy Turner Oct 05 '15 at 13:38

2 Answers2

1

TreeMap does not support concurrent removals.

You should use iterator's remove method

Iterator<Row> it = sheet.iterator();
while(it.hasNext())
{
    Row row = it.next();
    ... 
    it.remove();
}
James Wierzba
  • 16,176
  • 14
  • 79
  • 120
0

You don't appear to be using the row from the outer for loop, so you can remove it:

for(int rowNo=sheet.getLastRowNum()-1; rowNo >= 0;rowNo--) {
  row=sheet.getRow(rowNo);
  sheet.removeRow(row);
}

Note also that I'm iterating the rows backwards, so you don't end up only removing every other row.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243