功能:点击导出按钮,提交请求,下载excel文件;
第一步:跟后端童鞋确认交付的接口的response header设置了
![]()
以及返回了文件流。
第二步:修改axios请求的responseType为blob,以post请求为例:
axios({
method: 'post',
url: 'api/user/',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
},
responseType: 'blob'
}).then(response => {
this.download(response)
}).catch((error) => {
})
第三步:请求成功,拿到response后,调用download函数(创建a标签,设置download属性,插入到文档中并click)
methods: {
// 下载文件
download (data) {
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'excel.xlsx')
document.body.appendChild(link)
link.click()
}
}
转: https://www.cnblogs.com/yulj/p/8494465.html

本文详细介绍了如何在前端实现导出Excel文件的功能。通过与后端配合,设置正确的response header和返回文件流,利用axios发起blob类型请求获取数据,再通过创建a标签的方式触发文件下载。适用于希望增强数据导出能力的前端开发者。
301

被折叠的 条评论
为什么被折叠?



