2012-05-04 105 views
5

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

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


编辑(05.05.2012 - 15:53)

我试图解决BalusC在他的第一个link说,但如果我点击我的commandButton显示网页上的文件的内容。 mimetype可能有问题吗?

XHTML文件:

<a4j:form> 
    <a4j:commandButton action="#{surveyEvaluationBean.doDataExport}" value="#{msg.srvExportButton}" /> 
</a4j:form> 

主要豆:

public String doDataExport() { 

    try { 
     export.downloadFile(); 
    } catch (SurveyException e) { 
     hasErrors = true; 
    } 
    return ""; 
} 

出口豆:

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"); 
    } 
} 

编辑(05.05.2012 - 16:27)

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

回答

4

我需要保存在tomcat WEB-INF目录中第一个文件?

没有,只写它直接到HTTP响应体如您ExternalContext#getResponseOutputStream()已经设置适当的响应头,告诉浏览器是什么回事检索后获得。

做基于以下答案中发现的具体事例数学:

基本上是:

List<List<Object>> csv = createItSomehow(); 
writeCsv(csv, ';', ec.getResponseOutputStream()); 

顺便说一下,这类任务最喜欢的jsf组件是什么?

这是主观的。但无论如何,我们正在使用<p:dataExporter>来完全满意。

+0

我不认为我可以使用'PrimeFaces',因为他们不支持JSF 1.2,因为'PrimeFaces 2.0'当我是对的? –

+1

这是正确的,古老的JSF 1.x即将结束,因此您不应该期望新的组件库支持它。只需手动进行流式传输即可。您只需通过'ExternalContext#getResponse()'获取原始的'HttpServletResponse',然后调用它的'getOutputStream()',但这已在第一个链接中列出。或者,当然,升级到JSF 2.它提供了比JSF 1.2更多的优势。 – BalusC

+0

我知道jsf 1.2的缺点,但目前我们无法升级到更高级别。我试图理解你的第一个链接,但它不起作用。我使用了我在网上找到的mimetype'text /逗号分隔值',但浏览器(IE,FF,Chrome)没有正确解释它。 –

0

如果您使用的是JSF 2,则可以使用primefaces。
你可以看看那link

如果没有,你能做到这样的:

List<Object> report = new ArrayList<Object>(); // fill your arraylist with relevant data 
String filename = "report.csv";  
File file = new File(filename); 
Writer output = new BufferedWriter(new FileWriter(file)); 
output.append("Column1"); 
output.append(","); 
output.append("Column2"); 
output.append("\n"); 
//your data goes here, Replcae Object with your bean 
for (Object row:report){ 
    output.append(row.field1); 
    output.append(","); 
    output.append(row.field2); 
    output.append("\n"); 
} 
output.flush(); 
output.close();