使用POI API写入JAVA的Excel表

我正在使用follwing POI api通过java代码写入excel

public static HSSFWorkbook sampleWorkbook = new HSSFWorkbook(); public static HSSFSheet sampleDataSheet = sampleWorkbook.createSheet("ABC"); 

使用Java Main方法运行时工作正常。 但是当我用servlet将它转换成dao时,它只创build一次表单,之后显示以下exception

 java.lang.IllegalArgumentException: The workbook already contains a sheet of this name at org.apache.poi.hssf.usermodel.HSSFWorkbook.createSheet(HSSFWorkbook.java:813) at com.SangamOne.ApnaKhata.dao.ExcelReportGenerator1.generateSimpleExcelReport(ExcelReportGenerator1.jav a:309) at com.SangamOne.ApnaKhata.dao.ExcelReportGenerator1.getDealerxls(ExcelReportGenerator1.java:95) at com.SangamOne.ApnaKhata.Controller.Xlspass.doGet(Xlspass.java:29) at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 

 /*Just use the following check before creating a sheet: XSSFSheet sheet; XSSFWorkbook workBook (the workbook to hold the sheet having name sheetName) */ int sheetIndex = workBook.getSheetIndex(sheetName); if(sheetIndex == -1){ sheet = workBook.createSheet(sheetName); } /* If sheet with the given name does not already exist in the workbook, it will return -1, else the position of sheet in the workbook. */ 
 while (wb.getNumberOfSheets() > 1) wb.removeSheetAt(0); 

使用上面的代码来删除工作表。

我以前遇到过这个例外。 但是我的情况如下所示

workbook.createSheet(“超过Excel表名超过31个字符的非常非常非常长的名字”);

谷歌“Excel表名长度”。 不知道这是否是你面对的情况。 只是希望它有帮助。

谢谢