Delete an excel sheet using Apache POI

前端 未结 3 1461
轮回少年
轮回少年 2021-02-07 12:43

I have to delete a sheet from the Excel file.

Here\'s my code snippet :

FileInputStream fileStream = new FileInputStream(destFile);
POIFSFileSystem fsPo         


        
相关标签:
3条回答
  • 2021-02-07 13:06

    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();
    
    0 讨论(0)
  • 2021-02-07 13:07

    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.

    0 讨论(0)
  • 2021-02-07 13:13
    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);
                }
            }       
    }
    
    0 讨论(0)
提交回复
热议问题