javascript - Spring MVC 使用 javascript 下载 xls

标签 javascript java excel spring spring-mvc

我有一个 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/

相关文章:

Java:Runtime.getRuntime().exec() - 如何获取对已启动程序 JFrame 的引用?

excel - 类型不匹配错误,Nothing 且循环未终止

javascript - jQuery 范围(?)问题与最小案例演示

java - 如何传递 SSL keystore 密码?

javascript - 使用ajax将json/javascript数据/对象传递给c#函数

java - JPA - 创建临时主键

vba - 如何将 ActiveSheet、ActiveWorkbook 或 ThisWorkbook 设置为 VBA 中可选参数的默认值?

c# - 在特定工作表上打开 Excel 文件

javascript - 如何使带有文本的 html div 图像可供用户下载/保存?

JavaScript 密码验证不起作用