Vue 前端导出后端返回的excel文件

10次阅读

共计 885 个字符,预计需要花费 3 分钟才能阅读完成。

在网上搜索了一番之后,决定采用 Blob 方式,这也是大家推荐的一种的方式,特此做下记录。
页面:先筛选,向后端请求接口返回 excel 文件,代码如下:
const apiUrl = this.Global.httpUrl + ‘/laima/export/new/exportTackOutOrder’
console.log(this.form)
let param = new URLSearchParams();
param.append(“startDate”, “2019-01-01”);
param.append(“endDate”, “2019-02-01″);
this.$axios.post(apiUrl, param,{responseType: ‘blob’}).then((res) => {
console.log(res.data)
const link = document.createElement(‘a’)
let blob = new Blob([res.data],{type: ‘application/vnd.ms-excel’});
link.style.display = ‘none’
link.href = URL.createObjectURL(blob);
let num = ”
for(let i=0;i < 10;i++){
num += Math.ceil(Math.random() * 10)
}
link.setAttribute(‘download’, ‘ 外卖统计_’ + num + ‘.xlsx’)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
仔细看 axios 请求加了个 responseType: ‘blob’ 配置,这是很重要的
可以看到请求返回了一个 Blob 对象,你如果没有正确的加上 responseType: ‘blob’这个参数,返回的就不是个 Blob 对象,而是字符串了。然后就自动下载了!参考 https://blog.csdn.net/liujun03/article/details/84378942

正文完
 0