Delete an excel sheet using Apache POI

Venkat picture Venkat · Feb 19, 2013 · Viewed 24.3k times · Source

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

Answer

RainMaker picture RainMaker · Feb 19, 2013

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.