如何使用Ajax调用下载Excel? [英] How to download excel using ajax call?
本文介绍了如何使用Ajax调用下载Excel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从spring controllr返回了我的excel文件.但是文件没有转换.
I returned my excel file from spring controllr. but the file is not converting.
控制器:-
Workbook wb = services.downloadExcel(id);
response.setHeader("Content-disposition", "attachment;
filename=test.xls");
wb.write(response.getOutputStream());
response.flushBuffer();
return wb;
Ajax:-
$.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();
}
});
推荐答案
您使用的方法仅适用于纯文本文件,xls不是纯文本,因此您需要将其检索为二进制数据.
The method you're using will only work for plain text files, xls is not plain text so you need to retrieve it as binary data.
如果您使用的是jQuery 3+,则可以将请求的responseType设置为"blob",然后使用该blob来创建要下载的blob网址.
If you're using jQuery 3+ you can set the responseType of the request to 'blob' and use that blob to create your blob url for download.
jQuery 3 +
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();
}
});
这篇关于如何使用Ajax调用下载Excel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文