美文网首页
前端xlsx导出Excel文件

前端xlsx导出Excel文件

作者: Simple_Learn | 来源:发表于2021-02-04 17:51 被阅读0次

导出需要引入 https://www.npmjs.com/package/xlsx
核心代码如下:

      let s2ab = function (s) {
        if (typeof ArrayBuffer !== 'undefined') {
          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;
        } else {
          var buf = new Array(s.length);
          for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
          return buf;
        }
      };

            const header = ['name', 'abbrName']; //定义展示顺序
            const headerText = { name: '名称', abbrName: '缩写名称' };
            // https://www.npmjs.com/package/xlsx
            
            let arrList = [{name:'',abbrName:''},{name:'',abbrName:''}]
            const newData = [headerText, ...arrList];
            let fileName = '测试文件';

          
            let wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };

            //1.使用自定义表头
            wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(newData, { header: header, skipHeader: true });

            //2.使用表头
           // wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(arrList, { header: header });

            let out = XLSX.write(wb, {
              bookType: 'xlsx',
              bookSST: false,
              type: 'binary'
            });
            try {
              fileSaver.saveAs(new Blob([s2ab(out)], { type: 'application/octet-stream' }), fileName);
            } catch (e) {
              this.$message({
                type: 'error',
                message: '导出失败'
              });
            }
          }

主要是多做尝试,从文档中查看解决方法。
查看配置:


图片.png
图片.png

相关文章

网友评论

      本文标题:前端xlsx导出Excel文件

      本文链接:https://www.haomeiwen.com/subject/rvobtltx.html