Reputation: 2634
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
Upvotes: 17
Views: 31533
Reputation: 1333
Delete a sheet using Apache POI
// Open file
FileInputStream inputStream = new FileInputStream(new File(filePath));
XSSFWorkbook workBook = new XSSFWorkbook(inputStream);
// Delete Sheet
workBook.removeSheetAt(resultWorkbook.getSheetIndex("SheetToBeDeleted"));
// Save the file
FileOutputStream outFile =new FileOutputStream(new File(filePath));
workBook.write(outFile);
outFile.close();
Upvotes: 2
Reputation: 41
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);
}
}
}
Upvotes: 2
Reputation: 45060
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
.
Upvotes: 14