我们正在构建一个Spring boot REST终端点,用于生成一个大的XLS文件(可能包含约1百万行),并提供其下载。目前的解决方案使用Apache POI库的SXSSF API来创建工作簿; 之后,我们将工作簿写入输出流,将流收集到字节数组中,然后提供此字节数组进行下载。
如何对工作簿的内容进行流处理,以便在添加更多行时,不会将整个文件保存在内存中?
当前解决方案的代码:
如何对工作簿的内容进行流处理,以便在添加更多行时,不会将整个文件保存在内存中?
当前解决方案的代码:
@RequestMapping(path = "/download/xls", method = RequestMethod.GET, produces = org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<InputStreamResource> downloadXls(HttpServletResponse response, XlsRequest request) throws FileNotFoundException, InternalServerErrorException {
byte[] data = downloadIssuesAsExcel(response, request);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Description", "File Transfer");
headers.add("Content-Disposition", "attachment; filename=justAFile.xlsx");
headers.add("Content-Transfer-Encoding", "binary");
headers.add("Connection", "Keep-Alive");
headers.setContentType(
org.springframework.http.MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
InputStreamResource isr = new InputStreamResource(new ByteArrayInputStream(data));
return ResponseEntity.ok().contentLength(data.length).headers(headers).body(isr);
}
public byte[] downloadIssuesAsExcel(HttpServletResponse response, XlsRequest request)
throws InternalServerErrorException {
try {
SXSSFWorkbook workbook = createExcel(request, response);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
workbook.write(stream);
workbook.dispose();
workbook.close();
stream.close();
return stream.toByteArray();
} catch (Exception e) {
throw new InternalServerErrorException("IO exception while downloading XLS file", e);
}
}
我也试图将工作簿内容直接写在 response.getOutputStream() 中,但是文件以某种方式损坏了。
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Description", "File Transfer");
response.setHeader("Content-Disposition", "attachment; filename=" + issueDataService.getExcelName(request));
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Connection", "Keep-Alive");
SXSSFWorkbook workbook = createExcel(request, response);
workbook.write(response.getOutputStream());
workbook.dispose();
workbook.close();
response.getOutputStream()
的代码?可能有多种原因,例如是否指定了内容长度? - edwgiz