admin 管理员组文章数量: 1184232
导出excel,文件打不开
要注意responseType一定要设置
returnaxios({url:'/api/esb/ddi/db/export/excel',// url: '/test/db/export/excel',
params,method:'GET',//设置blob或者arraybufferresponseType:'blob',// responseType: 'arraybuffer',headers:{'Content-Type':'application/x-www-form-urlencoded'},}).then(res=>{
console.log(res);// 生产一个a标签let link = document.createElement('a')let blob =newBlob([res.data],{type:'application/vnd.ms-excel'})// let blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })// let blob = new Blob([res.data], { type: 'application/msexcel;charset=utf-8' })// 将a标签隐藏
link.style.display ='none'// 给a标签设置url
link.href =URL.createObjectURL(blob)
link.download = res.headers['content-disposition']//下载后文件名let name = link.download.split('=')[1]
name=decodeURIComponent(name)
link.download =name //下载的文件名// 将a标签添加在body中
document.body.appendChild(link)// 触发a标签
link.click()// 将a标签移除
document.body.removeChild(link)},error=>{
console.log(error);
ElMessage.error({showClose:true,message:'无数据',})})
看博客还看到他们出现了返回数据是乱码的问题,是因为
mock模块会影响原生的ajax请求,使得服务器返回的blob类型变成乱码
原文链接:
// 初始化 Response 相关的属性和方法
Util.extend(MockXMLHttpRequest.prototype,{responseURL:'',status: MockXMLHttpRequest.UNSENT,statusText:'',// ()-methodgetResponseHeader:function(name){// 原生 XHRif(!this.match){returnthis.custom.xhr.getResponseHeader(name)}// 拦截 XHRreturnthis.custom.responseHeaders[name.toLowerCase()]},// ()-method// getAllResponseHeaders:function(){// 原生 XHRif(!this.match){returnthis.custom.xhr.getAllResponseHeaders()}// 拦截 XHRvar responseHeaders =this.custom.responseHeaders
var headers =''for(var h in responseHeaders){if(!responseHeaders.hasOwnProperty(h))continue
headers += h +': '+ responseHeaders[h]+'\r\n'}return headers
},overrideMimeType:function(/*mime*/){},responseType:'',// '', 'text', 'arraybuffer', 'blob', 'document', 'json'response:null,responseText:'',responseXML:null})版权声明:本文标题:从普通Excel到诡异Blob,解读导出问题并寻找解决之道 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1772398671a3555484.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论