1. const docxtemplater = require('docxtemplater');
    2. const fs = require('fs');
    3. const path = require('path');
    4. const PizZip = require('pizzip');
    5. // 加载docx模板
    6. const content = fs.readFileSync(path.resolve(__dirname, '../public/TemplateDoc.docx'), 'binary');
    7. // 创建docx模板的zip对象
    8. const zip = new PizZip(content);
    9. // 创建docx模板的docxTemplater对象
    10. const doc = new docxtemplater(zip);
    11. let data = {
    12. name:'zhang',
    13. age:18
    14. }
    15. // 设置doc实际的参数
    16. doc.setData(data);
    17. // 渲染doc
    18. doc.render();
    19. // 导出数据
    20. const buf = doc.getZip().generate({type: 'nodebuffer'});
    21. // 写docx
    22. fs.writeFileSync(path.resolve(__dirname, `${dirName}/报告.docx`), buf);

    word模板:
    image.png
    输出:
    image.png