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

vue2+xlsx+xlsx-style+FileSaver实现复杂表格的下载

时间:2023-03-31 19:33:49 vue.js

感谢@robin的想法和建议。注意xlsx-style0.8.13错误需要在\node_modules\xlsx-style\dist\cpexcel.js中处理varcpt=require('./cpt'+'able');更改为varcpt=cptable;配置页:....从'file-saver'导入FileSaver;从'xlsx-style'导入XLSXS;从'xlsx'导入*asXLSX;exportdefault{data(){return{//Tabletable:{loading:false,loadingText:'',data:[],total:0,}};},created(){this.init();},methods:{/**导出按钮操作*/handleExport(excelName){this.table.loading=true;this.table.loadingText='正在导出,请稍候...';setTimeout(()=>{try{const$e=this.$refs['report-table'].$el;let$table=$e.querySelector('.el-table__fixed');if(!$table){$table=$e;}letwb=XLSX.utils.table_to_book($table,{raw:true});this.xlsxStyle(wb);varws=XLSXS.write(wb,{type:"buffer",});//constwbout=XLSX.write(wb,{bookType:'xlsx',bookSST:true,type:'array'});FileSaver.saveAs(newBlob([ws],{type:'application/octet-stream'}),`${excelName}.xlsx`,)}catch(e){if(typeofconsole!=='未定义')console.error(e);}this.table.loading=false;this.table.loadingText='';},1000);},xlsxStyle(wb){让ws=wb.Sheets["Sheet1"];for(letkeyinws){//console.log(key,ws[key])constnum=key.slice(1,key.length);//headerif(num==='1'&&ws[key].t!=='z'){//注意:没有开启border,如果开启了,会出现borderswhen的问题交叉行和列ws[key].s={font:{//字体相关样式名称:'宋体',//字体类型sz:11,//字体大小颜色:{rgb:''},//字体颜色粗体:true,//是否加粗},//border:{//top:{//style:"thin",//color:{//auto:1,//},//},//left:{//style:"thin",//color:{//auto:1,//},//},//right:{//style:"thin",//color:{//auto:1,//},//},//底部:{//样式:“薄”,//颜色:{//自动:1,//},//},//},对齐方式:{///自动换行wrapText:1,//centerhorizo??ntal:"center",vertical:"center",indent:0}}}else{//所有表格if(key!=='!rows'&&key!=='!cols'&&key!=='!ref'&&key!=='!fullref'&&ws[key].t!=='z'){ws[key].s={font:{//字体相关的样式名:"宋体",//fonttypesz:11,//fontsizecolor:{rgb:""},//fontcolor},//border:{//top:{//style:"thin",//color:{//auto:1,//},//},//left:{//style:"thin",//color:{//auto:1,//},//},//正确的:{//style:"thin",//color:{//auto:1,//},//},//bottom:{//style:"thin",//color:{//auto:1,//},//},//},alignment:{///automaticwrapText:1,//居中horizo??ntal:"center",vertical:"center",indent:0,},};}}}},},};目前满足复杂表的需求。只要能用el-table画出表格,导出格式就可以了。唯一的问题是导出表格中单元格的字体样式没有修改成功(解决)。可以使用xlsx-style插件修改单元格样式。