我有一个 Web 应用程序,我想在其中下载 xls 文件。 spring-boot 中的 Controller 将通过 get 请求返回一个 HttpServletResponse
:
@RequestMapping(method = RequestMethod.GET, value = "/export/{id}", produces = { "multipart/mixed", "multipart/form-data" })
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void export(@PathVariable String id, HttpServletResponse response) {
XSSFWorkbook wb = service.export(assessmentId);
String filename="test.xlsx";
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=test.xlsx");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
wb.write(bos);
byte[] barray = bos.toByteArray();
InputStream is = new ByteArrayInputStream(barray);
IOUtils.copy(is, response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
在客户端中,我想将文件导出到 xls,这是代码:
var blob = new Blob([data], {type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.style = "display: none";
a.href = objectUrl;
a.download = "test.xlsx";
document.body.appendChild(a);
a.click();
我在尝试打开 xlsx 文件时遇到文件损坏问题。
最佳答案
有什么理由让你不能只是 send the file as a download from the controller ?在 HTML 中使用类似
的内容<a href="/export/124875"><i class="fa fa-download"></i></a>
关于javascript - Spring MVC 使用 javascript 下载 xls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48663795/