java - 如何在 Spring RestController 中下载 excel 文件
问题描述
我正在使用 Apache POI 生成.xlsx文件。
我想从 Spring 控制器返回该文件。这是我到目前为止所做的:
控制器:
@RequestMapping(method = RequestMethod.GET)
public HttpEntity<byte[]> createExcelWithTaskConfigurations(HttpServletResponse response) throws IOException {
byte[] excelContent = excelService.createExcel();
HttpHeaders header = new HttpHeaders();
header.setContentType(new MediaType("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=my_file.xls");
header.setContentLength(excelContent.length);
return new HttpEntity<>(excelContent, header);
}
是否可以从 rest 控制器返回实际的 excel 文件,以便用户可以将其下载到他的计算机上?至于现在控制器返回 byte[] 但我想返回实际文件。我怎样才能做到这一点?
解决方案
您可以使用ByteArrayResource
作为文件下载。以下是您修改后的代码片段
@GetMapping(value="/downloadTemplate")
public HttpEntity<ByteArrayResource> createExcelWithTaskConfigurations() throws IOException {
byte[] excelContent = excelService.createExcel();
HttpHeaders header = new HttpHeaders();
header.setContentType(new MediaType("application", "force-download"));
header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=my_file.xlsx");
return new HttpEntity<>(new ByteArrayResource(excelContent), header);
}
如果您尝试使用 apache poi 生成 excel,请在下面找到代码片段
@GetMapping(value="/downloadTemplate")
public ResponseEntity<ByteArrayResource> downloadTemplate() throws Exception {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
XSSFWorkbook workbook = createWorkBook(); // creates the workbook
HttpHeaders header = new HttpHeaders();
header.setContentType(new MediaType("application", "force-download"));
header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=ProductTemplate.xlsx");
workbook.write(stream);
workbook.close();
return new ResponseEntity<>(new ByteArrayResource(stream.toByteArray()),
header, HttpStatus.CREATED);
} catch (Exception e) {
log.error(e.getMessage());
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
推荐阅读
- ruby-on-rails - Rails 弄乱了我的 Postgres TIME 列
- java - Spring Boot 仅在唯一时将角色添加到 DB
- python - 如何单击 selenium python 中的图标
- javascript - li 打开时允许在手风琴上移动滚动
- python-3.x - 使用带有子字符串/类似字符串的枚举函数
- java - 将十进制转换为二进制
- c# - 为什么返回 Task.CompletedTask 无法在异步方法中编译?
- can-bus - CANOpen 协议开销
- python - 我想为 transip api 生成一个 jwt
- excel - 尝试将来自 API 的响应放入工作表时,过程调用或参数无效(错误 5)