2017-10-13 55 views
0

我使用Apache POI从我的servlet下载“.xls”,因为它是我的servlet的名称和扩展名,所以文件的名称是“Download.xls”。Apache POI Servlet表已存在

当我第一次尝试下载文件时,它工作正常,但第二次显示错误。

java.lang.IllegalArgumentException: The workbook already contains a sheet named 'General Results' 

再次,我不想重写先前存在的文件,并且在使用它之后关闭输出流。

代码如下所示。

public class DownloadReports extends HttpServlet {// is maped as Download is xml 

     Workbook wb = new XSSFWorkbook(); 
<... more vars ...> 
public DownloadReports(){ 
<... initialize vars for styles ...> 
} 

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
     processRequest(request, response); 
     String report = request.getParameter("report"); 

if (report== null) { 
      report = ""; 
     } 

switch (report) { 
      case "Full": 
       generalReport(request, response); 
       break; 
default: 
<... Log attempt...> 
} 
} 

protected void reporteGeneral(HttpServletRequest request, HttpServletResponse response) { 
     ServletOutputStream fileOut = null; 
     try { 
.... 
Sheet fullReport = wb.createSheet("Full Report"); 
.... 
response.setContentType("application/vnd.ms-excel"); 
      fileOut = response.getOutputStream(); 
      //fileOut. 
      wb.write(fileOut); 
      wb.close(); 
      fileOut.close(); 
      fileOut.flush(); 
     } catch (Exception e) { 
<... log attempt ...> 
} 
}} 

部分代码ommited。

我想知道为什么它会覆盖现有文件,或者每次都有办法为工作簿创建新名称。

我怀疑这可能与我在工作簿外声明方法有关。

任何有助于理解正在发生的事情将会大大降低。

+1

代码的相关部分很可能是您创建/检索'wb'变量的位置。请包括这一点。也请附上整个堆栈跟踪。 – geert3

回答

2

您在servlet级别保留工作簿,并尝试在每个请求中添加一个新工作表。您应该为每个请求创建一个新的工作簿:

 ServletOutputStream fileOut = null; 
     try { 
.... 
Workbook wb = new XSSFWorkbook(); 
Sheet fullReport = wb.createSheet("Full Report"); 
.... 
response.setContentType("application/vnd.ms-excel"); 
      fileOut = response.getOutputStream(); 
      //fileOut. 
      wb.write(fileOut); 
      wb.close(); 
      fileOut.close(); 
      fileOut.flush(); 
     } catch (Exception e) { 
<... log attempt ...> 
} 
+0

就是这样,它解释了为什么它在我试图用WorkBook制作全球风格之前工作。谢谢,我会标记你的答案是正确的。 – Richard