zoukankan      html  css  js  c++  java
  • 优化: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;
      }

      

  • 相关阅读:
    UML(Unified Modeling Language)统一建模语言
    20、ASP.NET MVC入门到精通——WebAPI
    16、ASP.NET MVC入门到精通——MVC过滤器
    .net开发过程中Bin目录下面几种文件格式的解释
    13、ASP.NET MVC入门到精通——MVC请求管道
    15、ASP.NET MVC入门到精通——MVC-路由
    14、ASP.NET MVC入门到精通——Ajax
    10、ASP.NET MVC入门到精通——Model(模型)和验证
    12、ASP.NET MVC入门到精通——HtmlHelper
    8、ASP.NET MVC入门到精通——View(视图)
  • 原文地址:https://www.cnblogs.com/sanshao-ghf/p/11612566.html
Copyright © 2011-2022 走看看