const docxtemplater = require('docxtemplater');
const fs = require('fs');
const path = require('path');
const PizZip = require('pizzip');
// 加载docx模板
const content = fs.readFileSync(path.resolve(__dirname, '../public/TemplateDoc.docx'), 'binary');
// 创建docx模板的zip对象
const zip = new PizZip(content);
// 创建docx模板的docxTemplater对象
const doc = new docxtemplater(zip);
let data = {
name:'zhang',
age:18
}
// 设置doc实际的参数
doc.setData(data);
// 渲染doc
doc.render();
// 导出数据
const buf = doc.getZip().generate({type: 'nodebuffer'});
// 写docx
fs.writeFileSync(path.resolve(__dirname, `${dirName}/报告.docx`), buf);
word模板:
输出: