gpt4 book ai didi

java - Apache POI - 使用 XSSFWorkbok + servlet 响应

转载 作者:搜寻专家 更新时间:2023-11-01 03:56:49 25 4
gpt4 key购买 nike

我的 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’中发现不可读的内容。是否要恢复此工作簿的内容?....

尽管有这条消息,但电子表格可以正常打开,但我真的想删除这条消息。

有什么想法吗?

最佳答案

我知道这是一个非常古老的(6 年)但我在更新一些旧代码以从 HSSF 移动到 XSSF 之后来到这里,我的问题是缺少 jar xmlbeans-3.1.0.jar。错误已写入 TomCat 本地主机日志“java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject”

关于java - Apache POI - 使用 XSSFWorkbok + servlet 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15387243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com