vue 根据后台传回文件流导出excel
文章目录
由于业务需求,需要用到导出excel功能,后台传回的是文件流
因此前端需要做点儿处理才能导出
关键代码
this.$ajax.post('/ship/order/exportOrder',param,{ responseType: 'arraybuffer' }).then(res=>{
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob);
} else {
const aLink = document.createElement('a');
const blob = new Blob([res.data],{type: "application/vnd.ms-excel"});
// 创建一个当前文件的内存URL
const _href = URL.createObjectURL(blob);
aLink.style.display = 'none';
aLink.href = _href;
document.body.appendChild(aLink);
aLink.setAttribute('download', '订单数据.xlsx');
aLink.click();
document.body.removeChild(aLink);
// 手动释放创建的URL对象所占内存
URL.revokeObjectURL(_href);
}
})上面代码的关键在于 { responseType: 'arraybuffer' } 这个指定类型,之前忘记添加这个参数,虽然最后也能导出一个excel文件,但是打开的时候却得到报错 "此文件损坏无法加载";
所以这个不能少
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论