小试牛刀: 根据模板.docx, 下载完整详情报告.docx

131 阅读1分钟

前言: 如果一个功能需求, 前端和后端都能技术实现, 你怎么选? 选后端更安全稳定, 还是选前端更快捷方便?

后端实现: 根据模板.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`);
  });
};
3. templateDoc.docx 模板语法

微信图片_20240510174530.png

4.下载结果

微信图片_20240510175207.png

束语: 作为前端, 我可以选择沉默, 我不会我不知道, 甩给后端, 毕竟这种底层数据处理的是后端强项, 但职业尊重就是别人可以的你也可以。