我在其他地方看到过很多类似的问题,但一直无法解决这个问题。
我想使用 Apache POI (3.17) 在我的应用程序中下载 Excel 文档。我在 Spring 服务中生成文档,然后将其作为响应传递回 JavaScript 客户端以供下载。但是,由于“文件格式或文件扩展名无效”,文件已损坏。
Spring 服务:
final Workbook workbook = new XSSFWorkbook();
final Sheet sheet = workbook.createSheet("Test");
Row row = sheet.getRow(1);
if (row == null)
{
row = sheet.createRow(1);
}
Cell cell = row.getCell(0);
if (cell == null)
{
cell = row.createCell(0);
}
cell.setCellValue("Testing123");
final ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
workbook.write(outByteStream);
outArray = outByteStream.toByteArray();
outByteStream.flush();
outByteStream.close();
workbook.close();
Servlet:
final ByteArrayResource resource = new ByteArrayResource(
this.downloadService.downloadExcel(request, response, baseRequest));
final HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename());
return ResponseEntity.ok()
.headers(headers)
.contentLength(resource.contentLength())
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.body(resource);
JavaScript 客户端:
var contentTypeHeader = 'application/vnd.ms-excel';
var blob = new Blob([result],{type: contentTypeHeader});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
我哪里出错了?
最佳答案
好吧,我实际上已经弄清楚了。我找到了解决该问题的解决方案:
Getting corrupted file while exporting .xls file using java/javascript and apache POI
我需要在 servlet 中将文件编码为字符串,然后将其传递到客户端并解码为 Blob。
关于javascript - 从 servlet 响应中下载 JavaScript 中的 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58482636/