js读取本地word文档并修改文档内容

JSZipUtils 官方api:How to use JSZip

docxtemplater是一款强大的 Word、Powerpoint 和 Excel生成插件,他可以以参数的形式修改word模板的内容

模板:

js读取本地word文档并修改文档内容_第1张图片

 

import docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import JSZipUtils from "jszip-utils"

  JSZipUtils.getBinaryContent('/static/test.docx', (error, content) => {
        if (error) {
          throw error
        };

        var zip = new PizZip(content);
        var doc = new docxtemplater()

        doc.loadZip(zip);
        //获取数据
        doc.setData({
          name1: "张三",
          name2: "李四",
          name3: "2022-10-1",
        });
        try {
          doc.render()
        } catch (error) {
          var e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties,
          }
          console.log(JSON.stringify({
            error: e
          }));
          throw error;
        }
        var out = doc.getZip().generate({
          type: "blob",
          mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        })

        //下载
        const objectUrl = URL.createObjectURL(out)
        const link = document.createElement('a')
        link.href = objectUrl
        link.download = "test.docx"	//设置下载的文件名
        link.click()
        link.remove()
      })

你可能感兴趣的:(javascript,word,开发语言)