• 优化:vue纯前端导出excel表格


    一、安装依赖

      npm install xlsx --save

    二、引入依赖

      import XLSX from 'xlsx'

    三、构造导出数据

      exportExcel(){

        const tHeader = ['姓名','性别','地址','手机号’];

        const filterVal = ['name','sex','address','phone'];

        //列宽

        const cols = [{wpx:60},{wpx:60},{wpx:100},{wpx:60}];

        const data =this.formatJson(filterVal,this.exportData);//this.exportData是需要导出的json数据

        this.export_json_to_excel(tHeader,data,"个人信息表",cols);

      },

      formatJson ( filterVal,jsonData){

        return jsonData.map(v => filterVal.map( j => v [ j ] ));

      },

    四、构造Excel

      export_json_to_excel(tHeader,data,defaultTitle,cols){

        data.unshift ( tHeader );

        let ws_name = "Sheet1";

        let wb = XLSX.utils.book_new();

        let ws = XLSX.utils.aoa_to_sheet(data);

        if(cols.lengths>0){

          ws['!cols'] = cols;  //设置列宽

        }

        wb.SheetNames.push(ws_name);

        wb.Sheets[ws_name] = ws;

        let result = XLSX.write(wb,{bookType:'xlsx',bookSST:false,type:'binary'});

        let title = defaultTitle || '列表';

        this.openDownloadDialog(new Blob(this.s2ab(result)],{type:"application/octet-stream"}),title+".xlsx");

      },

    五、下载Excel

      openDownloadDialog(url, saveName){
        if(typeof url == 'object' && url instanceof Blob){
          url = URL.createObjectURL(url); // 创建blob地址
        }
        var aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
        var event;
        if(window.MouseEvent) {

          event = new MouseEvent('click');

        }else{
          event = document.createEvent('MouseEvents');
          event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        }
        aLink.dispatchEvent(event);
      },

       s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }

      

  • 相关阅读:
    01Servlet执行流程
    Tomcat配置虚拟主机
    Mac node 版本升级
    【微信小程序】【Demo】获取页面元素宽高,按相对百分比计算页面其他元素应设置宽度的像素数值。
    VM12解决出现与HyperV不兼容
    记录安装IDA插件Bindiff的坑
    C++ 正逆序迭代器
    智能指针虚析构函数基类指针访问子类方法
    编程最顶的八句格言
    visual studio C/C++ 创建使用动态库
  • 原文地址:https://www.cnblogs.com/sanshao-ghf/p/11612566.html
Copyright © 2020-2023  润新知