从JSF中的HttpServletResponse导出.xlsx文件 - 损坏错误

时间:2015-09-28 15:28:09

标签: jsf servlets apache-poi

我已经在这个问题上碰了一下我的脑袋已经有一段时间了,我已经公平地分享了现有的StackOverflow问题,这些问题与我的困境相似,但还没有找到解决方案对我有用。

我已经获得了一个带有HttpServletResponse的现有代码,并将其作为.xls附件导出,供用户下载。此代码在此处显示:

import java.io.IOException;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

/**
 * Action class to export data as a excel sheet.
 *
 */
public class ForecastReportExcel extends PageCodeBase {

public String exportExcel() throws IOException {
    HttpServletResponse response = (HttpServletResponse) FacesContext
            .getCurrentInstance().getExternalContext().getResponse();
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition",
            "attachment; filename=forecastReports.xls");
    return "success";
 }
}

我对此项目的要求只是将导出的文件从.xls文件更改为.xlsx文件。这看起来很简单。

我的第一次尝试是将MimeType更改为application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,将文件名更改为forecastReports.xlsx。从webapp下载导出的文件后,我收到错误 - Excel cannot open the file '[file].xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

所以,我去搜索并遇到了一些线程,其中人们建议使用Apache POI库,特别是用于.xlsx文件的XSSF库,以及写入OutputStream。所以,我给了它一个旋转:

import java.io.IOException;
import java.io.OutputStream;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * Action class to export data as a excel sheet.
 *
 */
public class ForecastReportExcel extends PageCodeBase {


public String exportExcel() throws IOException {
    XSSFWorkbook workbook = new XSSFWorkbook();
    HttpServletResponse response = (HttpServletResponse) FacesContext
            .getCurrentInstance().getExternalContext().getResponse();
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setHeader("Content-Disposition",
            "attachment; filename=forecastReports.xlsx");

    OutputStream outStream = response.getOutputStream();
    workbook.write(outStream);
    outStream.flush();
    outStream.close();
    return "success";
 }
}

当我下载导出的文件并在Excel中运行时,我收到消息We found a problem with some content in '[file].xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.点击“是”后,我得到The workbook cannot be opened or repaired by Microsoft Excel because it is corrupt.

另外,当我查看我的开发者控制台时,我看到打印出来的错误java.lang.IllegalStateException: Cannot forward. Response already committed.

我已经做了一些关于这意味着什么的搜索,但我发现它与此无关。现在,我非常困惑。有没有人看到我没有看到的任何东西?有人可以就我的错误给我一些指示吗?

非常感谢你们所提出的任何帮助或想法!

0 个答案:

没有答案