前言: 如果一个功能需求, 前端和后端都能技术实现, 你怎么选? 选后端更安全稳定, 还是选前端更快捷方便?
后端实现: 根据模板.docx 转成.xml代码, 再配合报告中的图表.ftl代码, 至少一万行代码起步
前端实现: 根据模板.docx, 配合 docxtemplater 插件, 不到500行代码完成
前端实现: 模板.docx 生成完整 企业报告.docx
1. 引入依赖插件
import docxtemplater from "docxtemplater";
import imageModule from "docxtemplater-image-module-free";
import PizZip from "pizzip";
import JSZipUtils from "jszip-utils";
import { saveAs } from "file-saver";
备注: vue3 需要将 templateDoc.docx 文件放在public文件目录下,vue2放在static文件目录下
2. 核心代码
const docDownload = (docSource) => {
JSZipUtils.getBinaryContent("/templateDoc.docx", function (error, content) {
if (error) {
throw error;
}
let zip = new PizZip(content);
let doc = new docxtemplater();
doc.attachModule(getImageModule());
doc.loadZip(zip);
doc.setData(docSource);
try {
doc.render();
} catch (error) {
let e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties,
};
console.log(
JSON.stringify({ error: e })
);
throw error;
}
let out = doc.getZip().generate({
type: "blob",
mimeType:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
saveAs(out, `${docSource.name}.docx`);
});
};