Search code examples
javaapache-poipoi-hssf

Delete an excel sheet using Apache POI


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


Solution

  • 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.