使用vue+elementUi+docxtemplater实现对列表页的doc文件导出,以及zip压缩包格式

使用vue+elementUi+docxtemplater实现对列表页的doc文件导出,以及zip压缩包格式

解决方案:

安装如下依赖

npm install --save docxtemplater pizzip jszip-utils jszip file-saver
npm install --save angular-expressions lodash

在utils里新建一个doc.js文件

import Docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import JSZipUtils from "jszip-utils";
import { saveAs } from "file-saver";
import JSZip from "jszip";

// 导出word压缩包
let expressions = require("angular-expressions");
let assign = require("lodash/assign");
expressions.filters.lower = function (input) {
  if (!input) return input;
  return input.toLowerCase();
};
function angularParser(tag) {
  tag = tag
    .replace(/^\.$/, "this")
    .replace(/(’|‘)/g, "'")
    .replace(/(“|”)/g, '"');
  const expr = expressions.compile(tag);
  return {
    get: function (scope, context) {
      let obj = {};
      const scopeList = context.scopeList;
      const num = context.num;
      for (let i = 0, len = num + 1; i < len; i++) {
        obj = assign(obj, scopeList[i]);
      }
      return expr(scope, obj);
    },
  };
}
export const exportDocx = (tempDocxPath, list, zipName) => {
  const promises = [];
  const zips = new JSZip();
  //  循环数据,生成word文件
  list.forEach((element, index) => {
    let fileName = zipName + "(" + index + ")" + ".docx"; // word文件名称
    let data = element;
    const promise = new Promise((resolver, reject) => {
      JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
        if (error) {
          throw error;
        }
        let zip = new PizZip(content);
        let doc = new Docxtemplater()
          .loadZip(zip)
          .setOptions({ parser: angularParser });
        doc.setData(data);
        try {
          doc.render();
        } catch (error) {
          throw error;
        }
        let out = doc.getZip().generate({
          type: "blob",
          mimeType:
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        });
        // 添至zip集合中
        zips.file(fileName, out, { binary: true });
        resolver();
      });
    });
    promises.push(promise);
  });

  // 下载zip包
  Promise.all(promises).then(() => {
    zips.generateAsync({ type: "blob" }).then((content) => {
      saveAs(content, zipName);
    });
  });
};

doc文件绘制:

新建docx文件,放置于public下,里面用{参数}写好
在这里插入图片描述

在页面中使用方法:

import { exportWord, exportDocx } from "@/utils/docx";

使用方法:
  // 导出
    handleDownload() {
      const data = [
        {
          title: "测试1",
          recorder: "记录人1",
        },
        {
          title: "测试2",
          recorder: "记录人2",
        },
      ];
      exportDocx("/施工日志记录.docx", data, `施工日志记录`);
    },
    

下载结果:

在这里插入图片描述

遇到问题:

  1. 依赖下载不了:如果依赖报错,单独安装angular-expressions 和lodash,或者用yarn
  2. 浏览器报错: Error: Can't find end of central directory : is this a zip file ?
    首先检查文件位置,放在public下面,或者static下面;
    其次看word文件里的参数是否规范(我遇见过参数不规范报这种错的);
    再次重新更新docx文件,移入最新的,有的时候会因为文件损坏(doc---->docx)而报错

参考链接:https://blog.csdn.net/dfdlife/article/details/127111742

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值