How to delete contents of an Excel sheet in Java?

落花浮王杯 提交于 2019-12-12 09:56:44

问题


How to delete contents of an Excel sheet in an Excel workbook, using Java SE and Apache POI?


回答1:


As mentioned in previous comments

Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
   sheet.removeRow(row);
}

this code throwing ConcurrentModificationException to me. So, I have modified the code and it's working fine. Here is the code:

Sheet sheet = wb.getSheetAt(0);
Iterator<Row> rowIte =  sheet.iterator();
while(rowIte.hasNext()){
    rowIte.next();              
    rowIte.remove();
}



回答2:


I've found that removeSheetAt/createSheet isn't really an acceptable answer, because you can't put the new sheet into the correct position in the workbook without running into a bug in WorkSheet.setSheetOrder

This code snippet

Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
   sheet.removeRow(row);
}

in my world throws a ConcurrentModificationException

I had to resort to

    for (int index = crnt.getLastRowNum(); index >= crnt.getFirstRowNum(); index--) {
        crnt.removeRow( crnt.getRow(index));
    }



回答3:


Depending on what contents you want to delete you may remove a single cell or row.

Too erase the complete sheet iterate over all rows and delete it.

Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
   sheet.removeRow(row);
}



回答4:


I know this is an old thread but I think I found the best solution

What I did was just create a new workbook of the same type and save it over the file that I wanted to delete.

Heres the code

private void clearOldFile(){
    FileOutputStream out = null;
    try{
        oldFile = new XSSFWorkbook();    
        Sheet sheet = oldFile.createSheet("temp data");

        out = new FileOutputStream(AbsolutePathForTempExcelFile);
        oldFile.write(out);
        out.close();

    } catch(Exception e){
        e.printStackTrace();
    }

}



回答5:


You probably want to use HSSFWorkbook.removeSheetAt(index).




回答6:


I also got concurrent modification exception, also using the more "modern" way of doing it :

sheet.forEach(r->sheet.remove(r));

The iterator based solution from @Thirupathi S apparently worked, but for reasons I don't exactly know it was creating xslx files that were not readable by Apple's Numbers and OSX preview (and probably other softwares too).

I suspect this has something to do with the iterator not removing something: the code of the removeRow method is way more complex than the simple iterator remove operation.

Using old plain for-loop with reversed index worked like a charm :

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



回答7:


This solution works fine with me. And also consider special cases, e.g. the sheet is blank, or the spaces between the firstRow and lastRow are present.

public void cleanSheet(Sheet sheet) {
    int numberOfRows = sheet.getPhysicalNumberOfRows();

    if(numberOfRows > 0) {
        for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
            if(sheet.getRow(i) != null) {
                sheet.removeRow( sheet.getRow(i));
            } else {
                System.out.println("Info: clean sheet='" + sheet.getSheetName() + "' ... skip line: " + i);
            }
        }               
    } else {
        System.out.println("Info: clean sheet='" + sheet.getSheetName() + "' ... is empty");
    }       
}



回答8:


I guess it is an old thread but I also get ConcurrentModificationException. Based on VoiceOfUnreason I found this to work:

        while (xlsSheet.getPhysicalNumberOfRows() > 0) {
          xlsSheet.removeRow(xlsSheet.getRow(xlsSheet.getLastRowNum()));
        }
        if (xlsSheet.getDrawingPatriarch() != null) {
          xlsSheet.getDrawingPatriarch().clear();
        }



回答9:


The other iterator methods appeared to work but Excel then refused to open the file. This one worked for me:

int rownum;
while ((rownum=sheet.getLastRowNum()) > 0) sheet.removeRow(sheet.getRow(rownum));


来源:https://stackoverflow.com/questions/6936956/how-to-delete-contents-of-an-excel-sheet-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!