如何使用ajax调用下载excel?

use*_*ser 1 ajax spring-mvc

我从 spring controllr 返回了我的 excel 文件。但文件没有转换。

控制器 : -

Workbook wb = services.downloadExcel(id);
response.setHeader("Content-disposition", "attachment; 
filename=test.xls");
wb.write(response.getOutputStream());
response.flushBuffer();
return wb;
Run Code Online (Sandbox Code Playgroud)

阿贾克斯:--

$.ajax({
    type: "GET",
    url: "/screener/" + projectId,
    success: function (result) {
        console.log(result)
        alert("sfa");
        var blob = new Blob([result], { type: 'application/vnd.ms- 
        excel' });
        var downloadUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "downloadFile.xls";
        document.body.appendChild(a);
        a.click();
    }
});
Run Code Online (Sandbox Code Playgroud)

Mus*_*usa 6

您使用的方法仅适用于纯文本文件,xls 不是纯文本,因此您需要将其作为二进制数据检索。

如果您使用的是 jQuery 3+,您可以将请求的响应类型设置为“blob”,并使用该 blob 创建用于下载的 blob url。

jQuery 3+

$.ajax({
    type: "GET",
    url: "/screener/" + projectId,
    xhrFields:{
        responseType: 'blob'
    },
    success: function (result) {
        console.log(result)
        alert("sfa");
        var blob = result;
        var downloadUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "downloadFile.xls";
        document.body.appendChild(a);
        a.click();
    }
});
Run Code Online (Sandbox Code Playgroud)