安装如下依赖
npm install --save docxtemplater pizzip jszip-utils jszip file-saver
npm install --save angular-expressions lodash
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);
});
});
};
import { exportWord, exportDocx } from "@/utils/docx";
使用方法:
// 导出
handleDownload() {
const data = [
{
title: "测试1",
recorder: "记录人1",
},
{
title: "测试2",
recorder: "记录人2",
},
];
exportDocx("/施工日志记录.docx", data, `施工日志记录`);
},
Error: Can't find end of central directory : is this a zip file ?
参考链接:https://blog.csdn.net/dfdlife/article/details/127111742