Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 530
Venkat Avatar asked Feb 19 '13 06:02

Venkat


3 Answers

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.

like image 134
Rahul Avatar answered Sep 19 '22 18:09

Rahul


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);
            }
        }       
}
like image 36
Hadjadj taha Avatar answered Sep 21 '22 18:09

Hadjadj taha


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(filePath);
  outFile.close();
like image 45
S Krishna Avatar answered Sep 21 '22 18:09

S Krishna