当前位置: 首页 > Web前端 > vue.js

前端pako.js解压,json转excel文件下载

时间:2023-03-31 21:43:49 vue.js

后台:后台返回:gzip压缩后的base64编码字符串。解决方法“Introducepako.js,xlsx”定义解压压缩的方法importXLSXfrom'xlsx'constpako=require('pako')代码://Downloaddownload(id){this.downloadLoading=id;api.dow??nload({id}).then(res=>{varstrData=atob(res.data);//将二进制字符串转换为字符数字数组varcharData=strData.split('').map(function(x){returnx.charCodeAt(0);});//将数字数组转换为字节数组varbinData=newUint8Array(charData);////解压vardata=pako.inflate(binData);//转换将byteArray压缩回ascii字符串:strData=String.fromCharCode.apply(null,newUint16Array(data));//转换中文乱码letjsonResult=decodeURIComponent(escape((strData)))console.log(jsonResult);//重新处理letexcel=JSON.parse(jsonResult).map(el=>{el['tagname']=el.tagValueel['id']=el.entity_iddeleteel.tagValuedeleteel.entity_idreturnel})//json转换excelthis.downMobileTempalte(excel)this.downloadLoading=null;}).catch(err=>{this.$Message.error(err);this.downloadLoading=null;})},//导出手机号excel模板downMobileTempalte(res){consttype='xlsx'constrs=resletdata=[{}]for(letkinrs[0]){data[0][k]=k}data=data.concat(rs)letkeyMap=[]//获取keyfor(letkindata[0]){keyMap.push(k)}lettmpdata=[]//用来保存转换后的jsondata.map((v,i)=>keyMap.map((k,j)=>Object.assign({},{v:v[k],位置:(j>25?this.getCharCol(j):String.fromCharCode(65+j))+(i+1)})))。reduce((prev,next)=>prev.concat(next)).forEach(function(v){tmpdata[v.position]={v:v.v}})letoutputPos=Object.keys(tmpdata)//设置区域,比如A1到D10的表格lettmpWB={SheetNames:['mySheet'],//保存的表格标题Sheets:{'mySheet':Object.assign({},tmpdata,//content{'!ref':outputPos[0]+':'+outputPos[outputPos.length-1]//设置填充区域})}}lettmpDown=newBlob([this.s2ab(XLSX.write(tmpWB,{bookType:(type===undefined?'xlsx':type),bookSST:false,type:'binary'}//这里data用于定义导出的格式类型))],{type:''})//创建一个二进制对象并写入转换后的字节流constlink=document.createElement("a");link.href=URL.createObjectURL(tmpDown)//创建对象超链接link.setAttribute("download","shoplabel.xls");document.body.appendChild(链接);链接.点击();setTimeout(function(){//延迟释放URL.revokeObjectURL(tmpDown)//使用URL.revokeObjectURL()释放这个对象URL},100)},//字符串转字符流s2ab(s){varbuf=newArrayBuffer(s.length)varview=newUint8Array(buf)for(vari=0;i!==s.length;++i){view[i]=s.charCodeAt(i)&0xFF}返回buf},//将指定的自然数转换为26进制表示映射关系:[0-25]->[A-Z]。getCharCol(n){lets='',m=0while(n>0){m=n%26+1s=String.fromCharCode(m+64)+sn=(n-m)/26}返回s}原作者:关爱单身狗成长协会