2011-05-06 75 views
6

我有一個Apache POI的問題。我嘗試在處理完相關數據後返回文件。當我將文件返回到瀏覽器(包括IE8/9,Firefox)時,瀏覽器會返回一個垃圾回收字符。這隻發生在Excel文件很大且進程已運行2分鐘以上的情況下。否則,它會返回一個文件,然後我可以在Excel中打開它。Apache POI輸出問題

任何幫助表示讚賞,謝謝。

response.setContentType("application/vnd.ms-excel"); 
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".xls\""); 
OutputStream out = null; 

try { 
    out = new BufferedOutputStream(response.getOutputStream()); 
    wb.write(out); 
    out.flush();  
} catch (IOException ex) { 
    ex.printStackTrace(); 
} 

回答

4

我想你應該指定內容的長度。這是你應該插入的行:

response.setContentLength(/* length of the byte[] */); 

我建議你使用Apache Commons IOUtils類來處理字節數組和流。

+0

謝謝你的回答,找到流的長度最好的方法是什麼? – Clive 2011-05-06 14:22:09

+0

我看不到'wb'類的變量。這是工作簿嗎?在這種情況下,我建議: ByteArrayOutputStream bos = new ByteArrayOutputStream(); wb.write(bos); response.setContentLength(bos.size()); response.getOutputSream()。write(bos.toByteArray()); response.getOutputStream()。flush(); response.getOutputStream()。close(); – jabal 2011-05-07 08:17:31