最近在做项目的时候遇到Excel导出功能,后端返回的是文件流,前端如何实现下载功能,以下是项目用的源码,有需要可直接复制使用:
// 导出
exporttable() {
this.axios({
method: "get",
url: this.baseUrls + "api/pcadmin/hr/entry/export",
responseType: "blob",
})
.then((response) => {
const content = response.data;
const blob = new Blob([content]);
const time = this.timestampToTime(new Date().getTime() / 1000);
const fileName = time + ".xlsx";
if ("download" in document.createElement("a")) {
// 非IE下载
const elink = document.createElement("a");
elink.download = fileName;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
} else {
// IE10+下载
navigator.msSaveBlob(blob, fileName);
}
// eslint-disable-next-line handle-callback-err
})
.catch((error) => { });
},