java - Apache POI - XSSFWorkbook + servlet 响应
问题描述
我发现使用 apache-poi 有问题。这是我的代码。
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(request.getSession().getServletContext().getRealPath("/Testing.xlsx")));
XSSFSheet spreadsheet = workbook.getSheet("TempSheet");
File template = new File(request.getSession().getServletContext().getRealPath("/Testing.xlsx"));
FileOutputStream out = new FileOutputStream(template);
workbook.write(out);
out.close();
String currentTime = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
String fileName = "TestingABC.xlsx";
String absoluteDiskPath = request.getSession().getServletContext().getRealPath("/Testing.xlsx");
File f = new File(absoluteDiskPath);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
InputStream in = new FileInputStream(f);
ServletOutputStream outs = response.getOutputStream();
try {
byte[] outputByte = new byte[4096];
while (in.read(outputByte, 0, 4096) != -1) {
outs.write(outputByte, 0, 4096);
}
outs.flush();
outs.close();
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(outs != null)
outs.close();
if(in != null)
in.close();
}catch (Exception ioe2) {
ioe2.printStackTrace();
}
}
}
Excel 文件可以正常下载,但是当我打开文件时,显示以下错误消息:“当我尝试此操作时,我收到消息:“我们发现 'TestingABC.xlsx' 中的某些内容存在问题。你想让我们尽可能多地恢复吗?如果您信任此工作簿的来源,请单击“是”
在我点击“是”后
错误如下:“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃。”
实际上,文件数据是正确的,但我怎样才能删除此消息?
谢谢。
解决方案
添加内容长度后它可以工作:
response.setContentLength((int) file.length());
推荐阅读
- .net-core - 在创建 HttpClient 的地方访问 HttpClientHandler
- mysql - phpmyadmin 中 mySQL 服务器上的表“使用中”
- laravel - 仅允许经过身份验证的用户访问 API 路由
- c++ - 如何将特定的内存地址分配给指针?
- javascript - 如何防止 setState 更改输入字段?
- javascript - 如何仅在 OnInit 之后启动 iterableDiffer?
- java - 云存储 1.88.0 访问输入流时出现异常
- tensorflow - 想知道输入和输出的列表以及张量流模型检查点的形状
- c++ - 如何使用 cmake 管理多个构建配置
- android - 与 FileProvider 共享文件时权限被拒绝