2017-10-13 58 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