美文网首页
js导出excel文件

js导出excel文件

作者: WangYatao | 来源:发表于2022-09-07 11:21 被阅读0次

    主要代码

    export const tableToExcel = (jsonData, header) => {
      // 循环遍历,每行加入tr标签,每个单元格加td标签
      for (let i = 0; i < jsonData.length; i++) {
        header += "<tr>";
        for (const key in jsonData[i]) {
          // 增加\t为了不让表格显示科学计数法或者其他格式
          header += `<td>${jsonData[i][key] + "\t"}</td>`;
        }
        header += "</tr>";
      }
      // Worksheet名
      const worksheet = jsonData[0].deptName;
      const uri = "data:application/vnd.ms-excel;base64,";
    
      // 下载的表格模板数据
      const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
            xmlns:x="urn:schemas-microsoft-com:office:excel"
            xmlns="http://www.w3.org/TR/REC-html40">
            <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
            <x:Name>${worksheet}</x:Name>
            <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
            </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
            </head><body><table>${header}</table></body></html>`;
      // 下载模板
      const link = document.createElement("a");
      link.href = uri + base64(template);
      // 对下载的文件命名
      link.download = `${worksheet}.xlsx`;
      link.click();
    };
    
    // 输出base64编码
    const base64 = (s) => window.btoa(unescape(encodeURIComponent(s)));
    

    调用方法

          const auditList = ["逻辑性审核", "合理性审核", "核实性审核"];
          const tableStr =
            "<tr><td>公司名称</td><td>所在报表</td><td>公式编码</td><td>审核类型</td><td>公式说明</td><td>提示内容</td><td>出错说明</td></tr>";
          const exportJson = this.errorList.map((item) => {
            const obj = {};
            let theReport = null;
            item.Row.forEach((item1) => {
              theReport = theReport
                ? theReport + ","
                : " " + item1.moduleCode + item1.moduleName;
            });
            obj["deptName"] = item.deptName;
            obj["theReport"] = theReport;
            obj["code"] = item.Code;
            obj["auditType"] = auditList[item.AuditType];
            obj["error"] = item.error;
            obj["formula"] = item.Formula;
            obj["errorMsg"] = item.errorMsg;
            return obj;
          });
          tableToExcel(exportJson, tableStr);
    

    相关文章

      网友评论

          本文标题:js导出excel文件

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