【问题标题】:Apache POI Servlet Sheet Already ExistsApache POI Servlet Sheet 已经存在
【发布时间】:2018-03-25 15:37:58
【问题描述】:

我正在使用 Apache POI 从我的 servlet 下载“.xls”,文件名是“Download.xls”,因为它是我的 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 ...>
}
}}

省略了一些代码。

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

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

非常感谢任何有助于了解正在发生的事情。

【问题讨论】:

  • 代码的相关部分可能是您创建/检索wb 变量的位置。请也包括在内。另外请附上整个堆栈跟踪。

标签: java servlets apache-poi fileoutputstream


【解决方案1】:

您将工作簿保留在 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 ...>
}

【讨论】:

  • 就是这样,它解释了为什么在我尝试使用 WorkBook 制作全局样式之前它会起作用。谢谢,我会将您的答案标记为正确。
猜你喜欢
  • 1970-01-01
  • 2013-03-01
  • 1970-01-01
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-20
  • 2018-04-29
相关资源
最近更新 更多