使用docxtemplater导出word文件
docxtemplater是一个用于生成和填充Word文档模板的JavaScript库。可以按照以下步骤使用docxtemplater来导出Word文件:
# 安装docxtemplater库:
npm install docxtemplater
1
# 创建模版
创建一个Word文档模板(.docx文件),并在文档中定义占位符,例如,用于后续替换。 在Node.js中编写代码,使用docxtemplater库加载Word文档模板并填充数据,然后将填充后的文档保存为新的Word文件。 模版内容如下:

# 导出word
const fs = require('fs');
const Docxtemplater = require('docxtemplater');
// 读取Word文档模板
const templateContent = fs.readFileSync('path/template.docx', 'binary');
// 创建docxtemplater实例
const doc = new Docxtemplater();
doc.loadZip(templateContent);
// 定义要填充的数据
const data = {
name: 'John Doe',
age: 30,
// 其他数据...
};
// 填充数据到文档模板
doc.setData(data);
doc.render();
// 将填充后的文档保存为新的Word文件
const buf = doc.getZip().generate({ type: 'nodebuffer' });
fs.writeFileSync('path/output.docx', buf);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
最总效果:

在这个示例中,我们首先读取Word文档模板,然后使用docxtemplater加载模板并填充数据,最后将填充后的文档保存为新的Word文件。记得替换示例代码中的模板路径和输出路径为你自己的实际路径。
注意
docxtemplater只支持docx格式的文档模版
上次更新: 2025/09/05, 8:09:00