使用JSF下载CSV文件

yve*_*ler 5 java csv jsf download

我不知道如何下载CSV文件.CSV将在运行时生成.我是否需要先将文件保存在tomcat WEB-INF目录中?我正在使用JSF 1.2.

顺便说一下,这种任务最受欢迎的JSF组件是什么?


编辑(05.05.2012 - 15:53)

我尝试了BalusC他的第一个链接中说明的解决方案,但如果我点击我的commandButton,该文件的内容将显示在网页上.也许这有问题mimetype

XHTML文件:

<a4j:form>
    <a4j:commandButton action="#{surveyEvaluationBean.doDataExport}" value="#{msg.srvExportButton}" />
</a4j:form>
Run Code Online (Sandbox Code Playgroud)

主豆:

    public String doDataExport() {

    try {
        export.downloadFile();  
    } catch (SurveyException e) {
        hasErrors = true;
    }
    return "";
}
Run Code Online (Sandbox Code Playgroud)

出口豆类:

public void downloadFile() throws SurveyException {

    try {

        String filename = "analysis.csv";

        FacesContext fc = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

        response.reset();
        response.setContentType("text/comma-separated-values");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

        OutputStream output = response.getOutputStream();

        // writing just sample data
        List<String> strings = new ArrayList<String>();

        strings.add("filename" + ";" + "description" + "\n");
        strings.add(filename + ";" + "this is just a test" + "\n");

        for (String s : strings) {
            output.write(s.getBytes());
        }

        output.flush();
        output.close();

        fc.responseComplete();

    } catch (IOException e) {
        throw new SurveyException("an error occurred");
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑(05.05.2012 - 16:27)

我解决了我的问题.我必须使用<h:commandButton>而不是<a4j:commandButton>现在它的工作原理!

Bal*_*usC 4

是否需要先将文件保存在tomcat WEB-INF目录下?

不,只需在设置正确的响应标头后将其直接写入 HTTP 响应正文即可ExternalContext#getResponseOutputStream(),该响应标头告诉浏览器它将检索什么。

根据以下答案中的具体示例进行数学计算:

基本上:

List<List<Object>> csv = createItSomehow();
writeCsv(csv, ';', ec.getResponseOutputStream());
Run Code Online (Sandbox Code Playgroud)

顺便问一下,对于此类任务,最喜欢的 jsf 组件是什么?

这是主观的。但无论如何,我们使用<p:dataExporter>得很满意。