Delete an excel sheet using Apache POI

女生的网名这么多〃 提交于 2019-12-20 18:05:56

问题


I have to delete a sheet from the Excel file.

Here's my code snippet :

FileInputStream fileStream = new FileInputStream(destFile);
POIFSFileSystem fsPoi = new POIFSFileSystem(fileStream);

HSSFWorkbook workbook = new HSSFWorkbook(fsPoi);

int index = 0;

HSSFSheet sheet = workbook.getSheet("Setup");
if(sheet != null)   {
    index = workbook.getSheetIndex(sheet);
    workbook.removeSheetAt(index);
}
return destFile;

After this I'm getting exactly the same workbook which I passed, without the removal of the sheet "Setup"

Help me resolve this. Any help would be appreciated


回答1:


After editing your workbook, you need to write it again. Try this:-

FileOutputStream output = new FileOutputStream(destFile);
workbook.write(output);
output.close();

Edit:- After writing it back, you can return your destFile.




回答2:


private void removeOtherSheets(String sheetName, XSSFWorkbook book) {       
        for(int i=book.getNumberOfSheets()-1;i>=0;i--){
            XSSFSheet tmpSheet =book.getSheetAt(i);
            if(!tmpSheet.getSheetName().equals(sheetName)){
                book.removeSheetAt(i);
            }
        }       
}


来源:https://stackoverflow.com/questions/14951378/delete-an-excel-sheet-using-apache-poi

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