无法使用HSSF Java删除Excel工作表

时间:2019-03-13 07:18:47

标签: java excel apache-poi indexoutofboundsexception hssfworkbook

我无法从工作簿中删除excel工作表。我尝试了其他解决方案,但无法解决。 说我要使用“ wb.RemoveSheetAt(5)”删除工作表编号5 我只能在删除工作表编号6之后将其删除。

代码:

public void cloneSheet(String sheetName , int NoOfClones){
    int temp = 0;
    for(int i = 0 ; i <= NoOfClones ; i++){
        HSSFSheet tsheet = workbook.cloneSheet(temp = workbook.getSheetIndex(sheetName));
        workbook.setSheetName((workbook.getSheetIndex(tsheet)), sheetName+i);   
    }
    workbook.removeSheetAt(workbook.getSheetIndex(sheetName));
}

这是我得到的错误:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 21, Size: 21
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at org.apache.poi.hssf.record.ExternSheetRecord.getRef(ExternSheetRecord.java:164)
at org.apache.poi.hssf.record.ExternSheetRecord.adjustIndex(ExternSheetRecord.java:168)
at org.apache.poi.hssf.model.LinkTable.updateIndexToInternalSheet(LinkTable.java:419)
at org.apache.poi.hssf.model.InternalWorkbook.removeSheet(InternalWorkbook.java:721)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.removeSheetAt(HSSFWorkbook.java:899)
at exceleditor.ExcelEditor.cloneSheet(ExcelEditor.java:104)
at exceleditor.QLaunchExcelEditor.main(QLaunchExcelEditor.java:290)

1 个答案:

答案 0 :(得分:0)

FileInputStream fileStream = new FileInputStream(excelFile);
POIFSFileSystem poiFS = new POIFSFileSystem(fileStream);
HSSFWorkbook workbook = new HSSFWorkbook(poiFS);
workbook.removeSheetAt(5);
FileOutputStream output = new FileOutputStream(excelFile);
workbook.write(output);
output.close();