vue使用 xlsx及xlsx-style导出表格(自定义表格样式)做法

涉及到合并单元+去网格线+总列数不固定的情况

使用的是xlsx文档,使用方法等同于SheetJS中文文档

  • 最终效果


    image.png

步骤1:安装xlsxxlsx

cnpm install xlsx --save
cnpm install xlsx-style --save
image.png

步骤2:修改xlsx-style插件包的代码

  • 修改1:找到 node_modules-----> xlsx-style---->dist---->cpexcel.js

807行将 var cpt = require('./cpt' + 'able');改为var cpt = cptable;

image.png
  • 修改2:找到 node_modules-----> xlsx-style---->ods.js

10行将 return require('../' + 'xlsx').utils;改为return require('./' + 'xlsx').utils;

image.png

  • 修改3:如果你的excel想要设置行高功能的话,xlsx-style是无法设置的,但是该功能xlsx是有的,因此将相关功能代码复制粘贴到xlsx-style中就可以让使其具有设置行高的功能。
    找到xlsx下的xlsx.js,复制如下两个截图代码到xlsx-style下的xlsx.js
var DEF_PPI = 96, PPI = DEF_PPI;
function px2pt(px) { return px * 96 / PPI; }
function write_ws_xml_data(ws, opts, idx, wb) {
    var o = [], r = [], range = safe_decode_range(ws['!ref']), cell="", ref, rr = "", cols = [], R=0, C=0, rows = ws['!rows'];
    var dense = Array.isArray(ws);
    var params = ({r:rr}), row, height = -1;
    for(C = range.s.c; C <= range.e.c; ++C) cols[C] = encode_col(C);
    for(R = range.s.r; R <= range.e.r; ++R) {
        r = [];
        rr = encode_row(R);
        for(C = range.s.c; C <= range.e.c; ++C) {
            ref = cols[C] + rr;
            var _cell = dense ? (ws[R]||[])[C]: ws[ref];
            if(_cell === undefined) continue;
            if((cell = write_ws_xml_cell(_cell, ref, ws, opts, idx, wb)) != null) r.push(cell);
        }
        if(r.length > 0 || (rows && rows[R])) {
            params = ({r:rr});
            if(rows && rows[R]) {
                row = rows[R];
                if(row.hidden) params.hidden = 1;
                height = -1;
                if(row.hpx) height = px2pt(row.hpx);
                else if(row.hpt) height = row.hpt;
                if(height > -1) { params.ht = height; params.customHeight = 1; }
                if(row.level) { params.outlineLevel = row.level; }
            }
            o[o.length] = (writextag('row', r.join(""), params));
        }
    }
    if(rows) for(; R < rows.length; ++R) {
        if(rows && rows[R]) {
            params = ({r:R+1});
            row = rows[R];
            if(row.hidden) params.hidden = 1;
            height = -1;
            if (row.hpx) height = px2pt(row.hpx);
            else if (row.hpt) height = row.hpt;
            if (height > -1) { params.ht = height; params.customHeight = 1; }
            if (row.level) { params.outlineLevel = row.level; }
            o[o.length] = (writextag('row', "", params));
        }
    }
    return o.join("");
}
image.png

image.png

image.png

步骤3:使用


  <script>
  import * as XLSX from 'xlsx' 
  import xlsxStyleObj from 'xlsx-style'
  export default {
    data() {
      return {
        maxNum:0,
        globalRowArray: [],
        // 网络数据,其中couponDetailList和otherCouponDetailList包含的数据的个数,最终决定有多少列数据
        allOrderListAll: [
          { "originalPayment": 251, "totalDiscountMoney": 22, "payment": 229, "couponName": "游泳消费券3", "discountMoney": 50, "enterpriseCouponName": "测试券1", "enterpriseCouponDiscountMoney": 22, "originalPrice": 360, "couponDetailList": [], "couponsDiscountMoney": 0, "otherCouponDetailList": [], "otherCouponsDiscountMoney": 50, "allInPayOrderNo": null, "price": 251, "title": null, "num": null, "accountNo": null, "benefitCategoryCode": null, "benefitCategoryName": null, "storeName": null, "couponList": null, "orderInfo": null, },
          { "originalPayment": 251, "totalDiscountMoney": 110, "payment": 141, "couponName": "体育消费券1", "discountMoney": 10, "enterpriseCouponName": null, "enterpriseCouponDiscountMoney": null, "originalPrice": 360, "couponDetailList": [{ "couponNo": "23J4J5HHLU ", "isOnline": null, "couponName": "体育消费券66", "discountMoney": 50, "couponId": null, "userId": null, "managerId": null }], "couponsDiscountMoney": 0, "otherCouponDetailList": [{ "couponNo": "1NAUJ885A3", "isOnline": null, "couponName": "体育消费券77", "discountMoney": 60, "couponId": null, "userId": null, "managerId": null }], "otherCouponsDiscountMoney": 50, "allInPayOrderNo": null, "price": 251, "title": null, "num": null, "accountNo": null, "benefitCategoryCode": null, "benefitCategoryName": null, "storeName": null, "couponList": null, "orderInfo": null, },
          { "originalPayment": 251, "totalDiscountMoney": 73, "payment": 178, "couponName": "体育消费券6", "discountMoney": 50, "enterpriseCouponName": "测试券34", "enterpriseCouponDiscountMoney": 43, "originalPrice": 360, "couponDetailList": [{ "couponNo": "4R1O833EUI", "isOnline": null, "couponName": "体育消费券5", "discountMoney": 30, "couponId": null, "userId": null, "managerId": null }], "couponsDiscountMoney": 0, "otherCouponDetailList": [], "otherCouponsDiscountMoney": 50, "allInPayOrderNo": null, "price": 251, "title": null, "num": null, "accountNo": null, "benefitCategoryCode": null, "benefitCategoryName": null, "storeName": null, "couponList": null, "orderInfo": null, }
        ]
      };
    },
    methods: {
       // 按钮点击
      exportBtn() {
          // 1、数据源设置
          for (var i = 0; i < this.allOrderListAll.length; i++) {// 动态向数据源中添加带有索引的couponName,discountMoney属性 并赋值,为的是在excel列中取出该属性的属性值并展示
            var list1 = [...this.allOrderListAll[i].couponDetailList];
            var list2 = [...this.allOrderListAll[i].otherCouponDetailList];
  
            if (list1.length || list2.length) {
              var list3 = [];
              list1.forEach(item => {
                list3.push(item);
              });
              list2.forEach(item => {
                list3.push(item);
              });
              for (var j = 0; j < list3.length; j++) {           
                // 必须修改数据源,这样导出的时候,自动匹配数据源中的key
                this.allOrderListAll[i]['couponName' + (j + 1)] = list3[j] ? list3[j].couponName : '';
                this.allOrderListAll[i]['discountMoney' + (j + 1)] = list3[j].discountMoney ? list3[j].discountMoney : '';
              }
            }
          }
  
          var couponCountList = [];
          for (var i = 0; i < this.allOrderListAll.length; i++) {// 统计数据中,最多使用了几张券
            couponCountList.push(this.allOrderListAll[i].couponDetailList.length + this.allOrderListAll[i].otherCouponDetailList.length);
          }
          console.log('couponCountList---',couponCountList);
          this.maxNum = Math.max(...couponCountList);// 所有数据中,找到每条数据中最多使用的券的张数. 用于计算excel中一共多少列数据
  
  
  
          // 2、表头设置
          let rowArray = [ // 3行
            ["核销结算表"],
            ["年  月  日    至", '', ''],
            ["商品原价(元)", "总优惠(元)","实付金额(元)"],
          ];

          for (var i = 0; i < this.maxNum; i++) {
            rowArray[1].push('');
            rowArray[1].push('');
            rowArray[2].push('惠民券名称' + (i + 1) + '');
            rowArray[2].push('惠民券金额' + (i + 1) + '(元)');  
          }
          rowArray[1].push('');
          rowArray[1].push('    年  月  日');
          rowArray[2].push('企业券名称');
          rowArray[2].push('企业券金额');

  
          // 3、表头对应字段设置
          var keyList = this.allOrderListAll.map((x, index) => {
          var tempList = [x.originalPayment, x.totalDiscountMoney, x.payment];

            for (var i = 0; i < this.maxNum; i++) {
              tempList.push(x["couponName" + (i + 1)]);
              tempList.push(x["discountMoney" + (i + 1)]);
            }
            tempList.push(x["enterpriseCouponName"]);
            tempList.push(x["enterpriseCouponDiscountMoney"]);
            return tempList;
  
          })
          var finalList = [];
          for (var i = 0; i < keyList.length; i++) {
            var dealList = [];
            for (var j = 0; j < keyList[0].length; j++) {
              dealList.push(keyList[i][j] == null ? '' : keyList[i][j]);
            }
            finalList.push(dealList);
          }

          const body = finalList;
  
          body.unshift(...rowArray);
          this.globalRowArray = rowArray;
          var monenyList = [];

  
          monenyList.push('汇总金额合计:');
          monenyList.push('');
          monenyList.push('');
  
          for (var i = 0; i < this.maxNum; i++) {
            monenyList.push('');
            monenyList.push('');
          }
          monenyList.push('');
          monenyList.push('');
 
          body.push(monenyList)

          var footerList = [];
          footerList.push('填表人:');
          footerList.push('');
          footerList.push('时间:');
          footerList.push('');
          footerList.push('单位:(盖章)');
          footerList.push('');
          body.push(footerList)
          const sheet = this.addStyleFunc(body);
          this.downloadFunc(this.sheetToBlobFunc(sheet),  rowArray[0] + '.xlsx');
      },

      // 将Blob下载到本地
      downloadFunc(data, filename) {
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {// IE浏览器使用 msSaveOrOpenBlob()方法下载
            window.navigator.msSaveOrOpenBlob(data, filename)// 兼容IE
        } else {// 其他浏览器
            const url = URL.createObjectURL(data);// 创建URL对象
            const link = document.createElement('a');// 创建a标签
            link.href = url;// 给a标签添加超链接
            link.download = filename;
            document.body.appendChild(link);// 模拟点击链接实现下载操作
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url); // 释放URL对象
        }
     },


      // 将sheet转成Blob
      sheetToBlobFunc(sheet) {
        var workbookJson = {
          SheetNames: ["zb_sheet1"],
          Sheets: {},
        };
        workbookJson.Sheets["zb_sheet1"] = sheet;
        // 配置excel的相关属性
        var workbookOptions = {
          bookType: "xlsx", // 要生成的文件类型
          bookSST: false, 
          showGridLines: false,// 是否显示网格线,默认为true
          type: "binary",
        };
        var generateFile = xlsxStyleObj.write(workbookJson, workbookOptions);
        var blobObj = new Blob([this.strToArrayBufferFunc(generateFile)], { type: "application/octet-stream" });
        return blobObj;
      },
      // 字符串转成ArrayBuffer
       strToArrayBufferFunc(str) {
          var buffer = new ArrayBuffer(str.length);
          var view = new Uint8Array(buffer);
          for (var i = 0; i !== str.length; ++i) view[i] = str.charCodeAt(i) & 0xff;
          return buffer;
        },
      // 为excel表格增加样式
      addStyleFunc(xlsx) {
        const sheet = XLSX.utils.aoa_to_sheet(xlsx);// 将JS数据的数组转换为工作表。
        console.log('----sheet---', sheet);// 包含着每行每列的相关信息(v: 单元格的值;t: 单元格的类型,b布尔值、n数字、e错误、s字符串、d日期;s: 单元格的样式)。空行空列不
        var mergeArr = []; // 要合并的单元格数组
        // const rowList = []; // 表格每列高度
        // 单元格边框-自定义边框样式
        const borderCustomer = {
          top: { style: "medium", color:{rgb: "000000"} },
          bottom: { style: "medium", color:{rgb: "000000"} },
          left: { style: "medium", color:{rgb: "000000"} },
          right: { style: "medium", color:{rgb: "000000"} },
        };
        // 单元格边框--去掉边框
        const borderCut = {
          top: { style: "" },
          bottom: { style: "" },
          left: { style: "" },
          right: { style: "" },
        };
  
        for (const key in sheet) {
          if (Object.hasOwnProperty.call(sheet, key)) {
            const element = sheet[key];
            console.log('sheet--', sheet, '---key---', key, '----element--', element);
            if (typeof element === "object") {// v: 单元格的值;t: 单元格的类型,b布尔值、n数字、e错误、s字符串、d日期;s: 单元格的样式
              // slice() 方法可从已有的数组中返回选定的元素。 
              // key如果为A234,那么key.slice(2),就从第2个索引开始,截到末尾,也就是34  (已验证)
              const index = Number(key.slice(1)) - 1;// 所有同行的,index一样。如A2和B2,得到的index都为1
              console.log('index---', index);
  
              element.s = {
                alignment: {
                  horizontal: "center", // 所有单元格剧中对其
                  vertical: "center", // 所有单元格垂直居中
                },
                font: {
                  name: "黑体",
                  sz: 10,
                  italic: false,
                  underline: false,
                },
                border: borderCustomer,
                fill: {
                  fgColor: { rgb: "FFFFFFFF" },
                },
              };
              
              // if (key.indexOf("H") != -1) {// key中有H,则右对齐。  -1表示没找到H。
              //   element.s.alignment.horizontal = "right";
              // }
              if (index === 0) {
                element.s.font.bold = true;
                element.s.font.sz = 24;
                element.s.border = borderCut;
                element.s.fill.fgColor = { rgb: "ffffff" };
              } else if (index === 1) {
                element.t = 's';
                element.s.alignment.horizontal = 'right';
                element.s.font.sz = 14;
                element.s.font.bold = true;
                element.s.border = borderCut;
              } else if (index === 2) {
                element.s.font.bold = true;
                element.s.fill.fgColor = { rgb: "FFD39B" };
                element.t = 's';
                element.s.font.sz = 13;
                element.s.font.color =  { rgb: "1C1C1C" }; /// FF00FF b8ddb0

              } else if (index === this.allOrderListAll.length + 3) {
                element.s.font.bold = true;
                element.s.font.sz = 20;
                element.s.font.name = 'Courier';
              } else if (index === this.allOrderListAll.length + 4) {
                element.s.font.bold = true;
                element.s.font.sz = 15;
                element.s.font.name = 'Courier';
                element.s.border = borderCut;
              }

  
            }
          }
        }
        let maxColumnNumber = 1; // 默认最大列数为1
        this.globalRowArray.map(item => item.length > maxColumnNumber ? maxColumnNumber = item.length : '');// 遍历每一行,找到最大列数
        console.log('--globalRowArray--', this.globalRowArray.length, '---maxColumnNumber--', maxColumnNumber);
        mergeArr = [
          { s: { c: 0, r: 0 }, e: { c: maxColumnNumber - 1, r: 0 } },
          { s: { c: 0, r: 1 }, e: { c: maxColumnNumber - 2, r: 1 } },
          { s: { c: 0, r: 3 + this.allOrderListAll.length }, e: { c: 1, r: 3 + this.allOrderListAll.length } },
          { s: { c: 0, r: 4 + this.allOrderListAll.length }, e: { c: 1, r: 4 + this.allOrderListAll.length } },
          { s: { c: 2, r: 4 + this.allOrderListAll.length }, e: { c: 3, r: 4 + this.allOrderListAll.length } },
          { s: { c: 4, r: 4 + this.allOrderListAll.length }, e: { c: 5, r: 4 + this.allOrderListAll.length } }
        ];
        sheet["!merges"] = mergeArr;
  
  
        // 单元格的列宽
        sheet['!cols'] = [];
        for(var i = 0;i < 5+this.maxNum*2;i++){
          var json = {wpx:200};
          sheet['!cols'].push(json);
        }
        // 单元格的行宽
        sheet['!rows'] = [];
        for(var i = 0;i < 5+this.allOrderListAll.length;i++){
          if(i == 0){
            var json = {hpx:58};
            sheet['!rows'].push(json);
          }else if(i == 1){
            var json = {hpx:38};
            sheet['!rows'].push(json);
          }else if(i == 2){
            var json = {hpx:32};
            sheet['!rows'].push(json);
          }else if(i == this.allOrderListAll.length + 3){
            var json = {hpx:58};
            sheet['!rows'].push(json);
          }else if(i == this.allOrderListAll.length + 4){
            var json = {hpx:58};
            sheet['!rows'].push(json);
          }else{
            var json = {hpx:26};
            sheet['!rows'].push(json);
          }
        }
        return sheet;
      },
    },
  
    mounted() {
  
  
    },
 
  };
  </script>
  
  
  <style scoped>

  </style>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容