2017-10-13 40 views
0

サーブレットから「.xls」をダウンロードするのにApache POIを使用しています。サーブレットの名前である拡張子に加えて、ファイル名は「Download.xls」です。Apache POIサーブレットシートが既に存在する

初めてファイルをダウンロードしようとすると、正常に動作しますが、2回目にエラーが表示されます。

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 ...> 
} 
}} 

一部のコードは省略されています。

Idは、既存のファイルを上書きしようとする理由、またはその都度ブックの新しい名前を作成する方法があるかどうかを知りたいと思っています。

私は、ワークブックをメソッドの外に宣言しているのと関係があると思われます。

何が起こっているのかを理解する助けがあれば、非常に感謝しています。

+1

「wb」変数を作成/取得する場所は、コードの関連する部分です。それも含めてください。また、スタックトレース全体を添付してください。 – geert3

答えて

2

サーブレットレベルでワークブックを作成し、リクエストごとに新しいシートを追加しようとしています。

 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