【发布时间】:2013-03-01 12:02:27
【问题描述】:
我的 java 应用程序无法下载 XLSX 文件。
按照此链接中显示的示例:Create an excel file for users to download using Apache POI,我尝试了两种配置来下载/保存电子表格。
首先使用 .XLS 文件:
response.setContentType("application/ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=testxls.xls");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue("Some text");
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
wb.write(outByteStream);
byte[] outArray = outByteStream.toByteArray();
OutputStream outStream = response.getOutputStream();
outStream.write(outArray);
outStream.flush();
这行得通。
然后我尝试使用 XLSX 文件:
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=testxls.xlsx");
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
cell.setCellValue("Some text");
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
wb.write(outByteStream);
byte[] outArray = outByteStream.toByteArray();
OutputStream outStream = response.getOutputStream();
outStream.write(outArray);
outStream.flush();
当我尝试此操作时,我收到消息:“Excel 在 'testxls.xlsx' 中发现了不可读的内容。是否要恢复此工作簿的内容?....” p>
尽管有此消息,电子表格仍可正常打开,但我真的想删除此消息。
有什么想法吗?
【问题讨论】:
-
outByteStream是什么类型? -
为什么需要
ByteArrayOutputStream?你不能简单地改用wb.write(response.getOutputStream())吗? -
我试过
org.apache.commons.io.output.ByteArrayOutputStream和java.io.ByteArrayOutputStream -
尝试使用
wb.write(response.getOutputStream()),但消息仍然存在。 -
如果您将 XSSFWorkbook 写入文件而不是 servlet,Excel 是否可以正确打开该文件?如果您有 servlet 输出问题或 XSSF 问题,这会让您解决问题
标签: java excel servlets apache-poi xlsx