使用vue+elementUi+docxtemplater实现对列表页的doc文件导出,以及zip压缩包格式
解决方案:
安装如下依赖
npm install --save docxtemplater pizzip jszip-utils jszip file-savernpm 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 = pile(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, `施工日志记录`);},
下载结果:
遇到问题:
依赖下载不了:如果依赖报错,单独安装angular-expressions 和lodash,或者用yarn浏览器报错:Error: Can't find end of central directory : is this a zip file ?
首先检查文件位置,放在public下面,或者static下面;
其次看word文件里的参数是否规范(我遇见过参数不规范报这种错的);
再次重新更新docx文件,移入最新的,有的时候会因为文件损坏(doc---->docx)而报错
参考链接:/dfdlife/article/details/127111742