美文网首页
vue+echarts+docx-template 前端导出wo

vue+echarts+docx-template 前端导出wo

作者: 无题syl | 来源:发表于2021-11-17 18:53 被阅读0次

功能参考链接

[docx-template](GitHub - guigrpa/docx-templates: Template-based docx report creation
)

需求

项目中,涉及到Echarts多个图,功能是,按照指定word(.docx)模板格式输出文档

步骤

1.vue 安装

 cnpm i docx-templates -S
    // jszip-utils 用于获取模板文件 template.docx,讲道理浏览器是不允许未经用户允许读取本地数据和写入数据到本地,因为这违反了浏览器的安全策略,所以有这个库我也很意外,要不然这个功能用这个库可能搞不起来,除非让用户主动上传模板,github给出的也是用户主动上传模板。这个文件我放在public目录底下,具体template.docx 文件样式我截图放在最后
 cnpm i jszip-utils -S 

2.引入

import JSZipUtils from 'jszip-utils';
/* 生成word */
const { createReport } = require('docx-templates');

3.放置对应的模板 template.docx


template.JPG

4.函数

   async toImageAllqd() {
//模板中数据
      let dqpd = [],
        wfbs = [],
        jcnl = [],
        kznl = [],
        otherItem = [],
        xlScore = 0,
        chScore = 0,
        otherScore = 0;
      this.loading = true;
      let params = {
        recordTime: localStorage.getItem("time"),
        baseDrillID: localStorage.getItem("taskId"),
      };
      let { data } = await this.$api.getScore(params);
      if (data.code === "200") {
        if (
          data.result !== null &&
          JSON.parse(data.result).tableData !== undefined
        ) {
          let obj = JSON.parse(data.result);
          obj.tableData.forEach((r) => {
            //敌情判断准确性  我方部署的合理性  决策能力 控制能力
            if (r.m_class === "敌情判断准确性") dqpd.push(r);
            if (r.m_class === "我方部署的合理性") wfbs.push(r);
            if (r.m_class === "决策能力") jcnl.push(r);
            if (r.m_class === "控制能力") kznl.push(r);
          });

          xlScore = obj.xlScore;
          chScore = obj.chScore;
          otherItem = obj.otherItem;
          otherScore = obj.otherScore;
        }
      }
      let urlList = [];
      var zgzs = this.$refs.zgzs.getElementsByTagName("canvas")[0],
        zcpl = this.$refs.zcpl.$el.getElementsByTagName("canvas")[0],
        zc = this.$refs.zc.getElementsByTagName("canvas")[0],
        grpl = this.$refs.grpl.$el.getElementsByTagName("canvas")[0],
        gr = this.$refs.gr.getElementsByTagName("canvas")[0],
        zcsl = this.$refs.zcsl.$el.getElementsByTagName("canvas")[0],
        grsl = this.$refs.grsl.$el.getElementsByTagName("canvas")[0];

      [zgzs, zcpl, zc, grpl, gr, zcsl, grsl].forEach((r, i) => {
        var arr = r.toDataURL("png");
        urlList.push(arr);
      });

      JSZipUtils.getBinaryContent(
        "./template.docx",
        async (error, template) => {
          // 抛出异常
          if (error) {
            throw error;
          }
          const report = await createReport({
            template,
            data: {
              //这个是你要放在 template.docx模板中的字段,这个变量后面会插入到template.docx模板中
              dqpd,
              wfbs,
              jcnl,
              kznl,
              otherItem,
              xlScore,
              chScore,
              otherScore,
            },
            // 这个对象里面的函数会在合成模板之前被执行
            additionalJsContext: {
              // 返回的格式如下, res 是图片 base64 编码

              getPicture: async (index) => {
                return {
                  width: 12,
                  height: 8,
                  data: urlList[index].replace(
                    /^data:image\/(png|jpg);base64,/,
                    ""
                  ),
                  extension: ".png",
                };
              },
            },
            // 这个属性定义了模板中变量的边界,例如template.docx中插入变量就可以使用{ creator }
            cmdDelimiter: ["{", "}"],
          });
          this.saveDataToFile(
            report,
            localStorage.getItem("name") +'_'+ new Date().getHours()+'_'+new Date().getMinutes()+'_'+new Date().getSeconds(), //文件名称
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
          );
        }
      );

      // 下载按钮方法结束
    },
    /* 下载word文件 */
    async saveDataToFile(data, fileName, mimeType) {
      const blob = new Blob([data], { type: mimeType });
      const url = window.URL.createObjectURL(blob);
      this.downloadURL(url, fileName, mimeType);
      setTimeout(() => {
        window.URL.revokeObjectURL(url);
      }, 1000);
    },
    async downloadURL(data, fileName) {
      const a = document.createElement("a");
      a.href = data;
      a.download = fileName;
      document.body.appendChild(a);
      a.style = "display: none";
      a.click();
      a.remove();

      this.loading = false;
    },

word模板中的模板格式

循环模板


bob.JPG

图片模板


image.JPG

相关文章

网友评论

      本文标题:vue+echarts+docx-template 前端导出wo

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