我在我的Java应用程序中遇到问题以启用下载XLSX文件。Apache POI - 使用XSSFWorkbok + servlet响应
以下示例显示在此链接中: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’不可读的内容你要恢复的内容此工作簿?...“
尽管出现此消息,电子表格会正常打开,但我真的想要删除此消息。
任何想法?
什么类型是'outByteStream'? – 2013-03-13 14:10:38
为什么你需要一个'ByteArrayOutputStream'?你不能简单地用'wb.write(response.getOutputStream())'来代替吗? – 2013-03-13 14:17:11
我尝试过使用'org.apache.commons.io.output.ByteArrayOutputStream'和 'java.io.ByteArrayOutputStream' – 2013-03-13 14:26:27