2017-01-23 98 views
0

嗨我一直在努力編寫代碼,以便我可以生成一個Excel工作表,並在用戶點擊下載按鈕時下載它....我成功地生成了Excel工作表但我已經嘗試下載相同,但我一直不成功。無法使用JSF下載excel文件

我已經使用的方法是:

public void download() throws IOException { 
    File file = new File("D:\\pdf\\carrierReport7.xls"); 

    FacesContext facesContext = FacesContext.getCurrentInstance(); 

    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); 

    response.setHeader("Content-Disposition", "attachment;filename=" + file.getName()); 
    response.setHeader("Content-Type", "application/vnd.ms-excel"); 

    OutputStream outputStream = response.getOutputStream(); 

    FileInputStream fileInputStream = new FileInputStream(file); 

    byte[] bytesBuffer = new byte[2048]; 

    int bytesRead = 0; 

    while ((bytesRead = fileInputStream.read(bytesBuffer)) > 0) { 
     outputStream.write(bytesBuffer, 0, bytesRead); 
    } 

    outputStream.flush(); 

    fileInputStream.close(); 
    outputStream.close(); 

    facesContext.responseComplete(); 
} 

JSF命令:

+1

您是否看到錯誤/異常?當你嘗試這些功能時,是否真的會下載到你的瀏覽器? –

+0

嘗試在stackoverflow中找到其中一個重複項,並檢查它們的哪一部分可以幫助您。而尼古拉斯史密斯是對的......你可以也應該提供更多的信息。 – Kukeltje

+0

沒有錯誤。它只是處理請求而沒有響應。也沒有什麼是下載。我嘗試了不同的代碼已經在stackoverflow給出,但仍然面臨同樣的問題。我是否需要在web.xml或瀏覽器設置中進行任何更改 –

回答

0

這就是我正在做類似的事情在JSF 2,不知道你是什麼版本。

public void downloadAttachment(Attachment attachment) throws IOException { 
    FacesContext fc = FacesContext.getCurrentInstance(); 
    ExternalContext ec = fc.getExternalContext(); 

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide. 
    ec.setResponseContentType(ec.getMimeType(attachment.getFilename()));   
    ec.setResponseContentLength(attachment.getFilesizeBytes().intValue()); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown. 
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + attachment.getFilename() + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead. 

    OutputStream output = ec.getResponseOutputStream(); 
    output.write(attachment.getFileData()); 

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed. } 

} 
+0

我試過了你提到的代碼,但仍然是同樣的問題。它不會下載任何東西。 –