纯前端用XLSX库导出excel,可含多个sheet

2021-09-10  本文已影响0人  波仔_4867

缺点就是不能设置表头宽度且内容不能居中

导出excel的逻辑:

excel整个表格专业名词是workbook,里面每张表格是sheet
页面引入xlsx的库,https://unpkg.com/xlsx/dist/xlsx.core.min.js
把数据生成sheet,var sheet = XLSX.utils.json_to_sheet(jsonData),json_to_sheet是将由对象组成的数组转化成sheet,当然还有 aoa_to_sheet将一个二维数组转成sheet 和 table_to_sheet将table的dom直接转成sheet
创建虚拟的workbook,var wb = XLSX.utils.book_new()
把sheet添加到workbook里,XLSX.utils.book_append_sheet(wb, sheet, "这里是sheetName");
把workbook转成blob,var blob = workbook2blob(wb),这里workbook2blob需要手动写啦,下面会贴代码
利用a标签和createObjectURL实现下载功能,openDownloadDialog(blob, 'excel的标题.xlsx');,这里openDownloadDialog也会在下面放上代码

import XLSX from "xlsx";

 //按学生统计
            let students = data.obj.students.map((v, i) => {
              return {
                序号: i + 1,
                学生姓名: v.studentname,
                学生账号: v.loginname,
                所属班级: v.classname
                  ? getGradeName(v.gradeid) + v.classname
                  : "",
                收到作业次数: v.sdnum,
                提交作业次数: v.commitnum,
                提交率: v.commitrate + "%",
                得分率: v.scorerate + "%"
              };
            });
            //按科目统计
            let subjects = data.obj.subjects.map((v, i) => {
              return {
                序号: i + 1,
                学生姓名: v.studentname,
                学生账号: v.loginname,
                所属班级: v.classname
                  ? getGradeName(v.gradeid) + v.classname
                  : "",
                所属科目: v.subjectname ? v.subjectname : "",
                科目作业: v.sdnum,
                已提交作业: v.commitnum,
                提交率: v.commitrate + "%",
                得分率: v.scorerate + "%"
              };
            });
            const sheet1 = XLSX.utils.json_to_sheet(students);
            const sheet2 = XLSX.utils.json_to_sheet(subjects);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, sheet1, "按学生统计");
            XLSX.utils.book_append_sheet(wb, sheet2, "按科目统计");
            const workbookBlob = this.workbook2blob(wb);
            let da = new Date(this.form_stu.starttime * 1000);
            var year = da.getFullYear() + "年";
            var month = da.getMonth() + 1 + "月";
            var date = da.getDate() + "日";
            let starttime = year + month + date;
            let das = new Date(this.form_stu.stoptime * 1000);
            var years = das.getFullYear() + "年";
            var months = das.getMonth() + 1 + "月";
            var dates = das.getDate() + "日";
            let stoptime = years + months + dates;
            let excelName = starttime + "-" + stoptime + "作业统计";
            // 导出最后的总表
            this.openDownloadDialog(workbookBlob, excelName + ".xlsx");

   workbook2blob(workbook) {
      // 生成excel的配置项
      var wopts = {
        // 要生成的文件类型
        bookType: "xlsx",
        // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
        bookSST: false,
        type: "binary"
      };
      var wbout = XLSX.write(workbook, wopts);
      // 将字符串转ArrayBuffer
      function 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;
      }
      let buf = s2ab(wbout);
      var blob = new Blob([buf], {
        type: "application/octet-stream"
      });
      return blob;
    },
    // 将blob对象 创建bloburl,然后用a标签实现弹出下载框
    openDownloadDialog(blob, fileName) {
      if (typeof blob === "object" && blob instanceof Blob) {
        blob = URL.createObjectURL(blob); // 创建blob地址
      }
      var aLink = document.createElement("a");
      aLink.href = blob;
      // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,有时候 file:///模式下不会生效
      aLink.download = fileName || "";
      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);
    },
上一篇下一篇

猜你喜欢

热点阅读