2011-05-06 76 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