使用Apache POI删除Excel工作表

时间:2013-02-19 06:44:44

标签: java apache-poi poi-hssf

我必须从Excel文件中删除一张表。

这是我的代码段:

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;

在此之后,我获得完全相同的工作簿,而不删除工作表“设置”

帮我解决这个问题。任何帮助将不胜感激

3 个答案:

答案 0 :(得分:12)

编辑工作簿后,需要再次编写。试试这个: -

FileOutputStream output = new FileOutputStream(destFile);
workbook.write(output);
output.close();

修改: - 写完后,您可以退回destFile

答案 1 :(得分:1)

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);
            }
        }       
}

答案 2 :(得分:0)

使用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();