2012-05-04 163 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();