关于 Word Document Creator
Word Document Creator 是一项使用 Node.js 库生成 Microsoft Word(.docx)文件的技能,支持从头创建或套用模板,并可生成格式化内容和批量文档。
主要功能
- 01创建格式化 .docx 文件
- 02根据模板生成文档
- 03添加表格和图像
- 04批量生成个性化文档
- 05配置样式和页面布局
适用场景
- 01制作格式化信件和报告
- 02将变量数据填入模板
- 03创建含表格和图像的文档
- 04根据数据源生成个性化文件
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ jmsktm/ claude-settings --skill word-document-creator安装后在 Claude Code 中输入/word-document-creator确认已加载。
详细介绍
Word 文档创建器
Word 文档创建器技能提供了全面的功能,可通过编程方式生成 Microsoft Word(.docx)文档。它使用 Node.js 的 docx 库处理格式、样式、表格、图片、页眉、页脚和复杂布局。此技能对于自动生成文档、创建报告以及基于模板的工作流至关重要。
无论是简单的信件,还是包含表格、图表、图片和自定义样式的复杂报告,都可以轻松创建。此技能支持从头创建,也支持基于模板生成并替换变量。
核心工作流
工作流 1:从头创建格式化文档
用途: 创建包含标题、段落、列表和格式的 Word 文档
步骤:
- 导入
docx库并创建 Document 实例 - 为标题、正文和列表定义样式
- 添加包含页眉和页脚的节
- 创建带格式的段落(粗体、斜体、颜色、对齐方式)
- 添加编号列表和项目符号列表
- 插入带格式的表格
- 导出为 .docx 文件
实现:
const { Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType } = require('docx');
const fs = require('fs');
async function createDocument(outputPath) {
const doc = new Document({
sections: [{
properties: {},
headers: {
default: new Header({
children: [new Paragraph({ text: "Company Name", alignment: AlignmentType.RIGHT })]
})
},
children: [
new Paragraph({
text: "Business Proposal",
heading: HeadingLevel.HEADING_1,
alignment: AlignmentType.CENTER
}),
new Paragraph({
children: [
new TextRun({ text: "Prepared for: ", bold: true }),
new TextRun("Client Name")
]
}),
new Paragraph({
text: "Executive Summary",
heading: HeadingLevel.HEADING_2
}),
new Paragraph({
text: "This proposal outlines the scope, timeline, and budget for the project...",
alignment: AlignmentType.JUSTIFIED
})
]
}]
});
const buffer = await Packer.toBuffer(doc);
fs.writeFileSync(outputPath, buffer);
}
工作流 2:从模板生成文档
用途: 使用 Word 模板文件,并用实际数据替换占位符
步骤:
- 使用
pizzip和docxtemplater加载模板 .docx 文件 - 定义包含替换值的数据对象
- 将数据设置到模板中
- 渲染模板并替换内容
- 处理重复部分(表格、列表)的循环
- 处理图片和条件部分
- 导出最终文档
实现:
const Docxtemplater = require('docxtemplater');
const PizZip = require('pizzip');
const fs = require('fs');
function generateFromTemplate(templatePath, data, outputPath) {
const content = fs.readFileSync(templatePath, 'binary');
const zip = new PizZip(content);
const doc = new Docxtemplater(zip, {
paragraphLoop: true,
linebreaks: true
});
// Data object with placeholder values
doc.setData({
clientName: data.clientName,
projectName: data.projectName,
date: new Date().toLocaleDateString(),
items: data.items, // Array for looping
total: data.total
});
doc.render();
const buf = doc.getZip().generate({
type: 'nodebuffer',
compression: 'DEFLATE'
});
fs.writeFileSync(outputPath, buf);
}
// Template placeholders: {clientName}, {projectName}, etc.
// Loop syntax: {#items}{name} - {price}{/items}
工作流 3:创建包含表格和图片的文档
用途: 创建包含数据表格和嵌入图片的复杂文档
步骤:
- 创建 Document 实例
- 定义包含行和列的表格
- 设置单元格格式(边框、底纹、对齐方式)
- 添加粗体样式的表头
- 填充数据行
- 插入并设置图片的大小和位置
- 为图片添加题注
- 导出文档
实现:
const { Document, Packer, Paragraph, Table, TableRow, TableCell, Media } = require('docx');
const fs = require('fs');
async function createTableDocument(data, imagePath, outputPath) {
const image = Media.addImage(doc, fs.readFileSync(imagePath), 300, 200);
const doc = new Document({
sections: [{
children: [
new Paragraph({ text: "Sales Report Q4 2025", heading: HeadingLevel.HEADING_1 }),
new Table({
rows: [
// Header row
new TableRow({
children: [
new TableCell({ children: [new Paragraph({ text: "Month", bold: true })] }),
new TableCell({ children: [new Paragraph({ text: "Revenue", bold: true })] }),
new TableCell({ children: [new Paragraph({ text: "Growth", bold: true })] })
]
}),
// Data rows
...data.map(row => new TableRow({
children: [
new TableCell({ children: [new Paragraph(row.month)] }),
new TableCell({ children: [new Paragraph(row.revenue)] }),
new TableCell({ children: [new Paragraph(row.growth)] })
]
}))
]
}),
new Paragraph({ text: "" }), // Spacing
new Paragraph({ text: "Revenue Trend Chart", heading: HeadingLevel.HEADING_2 }),
new Paragraph({ children: [image] }),
new Paragraph({ text: "Figure 1: Quarterly Revenue Trend", italics: true })
]
}]
});
const buffer = await Packer.toBuffer(doc);
fs.writeFileSync(outputPath, buffer);
}
工作流 4:批量生成文档
用途: 从数据源创建多份个性化文档
步骤:
- 加载数据源(JSON、CSV、数据库)
- 加载文档模板
- 对每条记录:
- 创建新的文档实例
- 填入记录数据
- 应用格式
- 使用唯一文件名保存
- 跟踪每份文档的成功或失败状态
- 生成汇总报告
工作流 5:添加高级格式
用途: 应用样式、字体、颜色、间距和页面布局
步骤:
- 在文档中定义自定义样式
- 创建样式层级(标题级别、正文、题注)
- 设置字体系列、字号和颜色
- 配置段落间距和缩进
- 设置页边距和页面方向
- 添加页码和分节符
- 应用主题和配色方案
实现:
const doc = new Document({
styles: {
paragraphStyles: [
{
id: "CustomHeading",
name: "Custom Heading",
basedOn: "Heading1",
next: "Normal",
run: {
size: 32,
bold: true,
color: "2E74B5",
font: "Calibri"
},
paragraph: {
spacing: { before: 240, after: 120 }
}
}
]
},
sections: [{
properties: {
page: {
margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 } // 1440 = 1 inch
}
},
children: [
new Paragraph({ text: "Styled Heading", style: "CustomHeading" })
]
}]
});
快速参考
| 操作 | 命令/触发语 |
|---|---|
| 创建新文档 | "创建 Word 文档 [name]" |
| 使用模板 | "从模板生成 docx [file]" |
| 添加表格 | "向 [doc] 添加包含 [rows] 行的表格" |
| 插入图片 | "将 [image] 插入 Word 文档" |
| 批量生成 | "为每个 [data] 创建 Word 文档" |
| 应用样式 | "使用 [style] 格式化 Word 文档" |
| 添加页眉/页脚 | "向文档添加页眉 [text]" |
| 创建目录 | "生成目录" |
最佳实践
- 优先使用样式而非直接格式设置: 定义并使用样式,以保持一致性并便于更新
- 模板: 为重复使用的文档类型(合同、报告、信函)使用模板
- 页面布局: 在创建文档时尽早设置页边距、方向和纸张大小
- 表格: 使用表格样式,获得专业外观并便于维护
- 图像: 嵌入前压缩图像;使用合适的分辨率(150-300 DPI)
- 页眉/页脚: 保持简洁,并在各个部分保持一致
- 文件大小: 监控文档大小;避免不必要地嵌入高分辨率图像
- 兼容性: 如果面向广泛的受众,请在不同版本的 Word 中测试文档
- 数据验证: 替换模板内容前验证输入数据,以避免错误
- 错误处理: 妥善处理缺失的模板占位符
- 版本控制: 对不断演进的文档类型使用模板版本管理
- 无障碍访问: 使用适当的标题层级,并为图像添加替代文本
常见模式
会议纪要:
const doc = new Document({
sections: [{
children: [
new Paragraph({ text: "Meeting Minutes", heading: HeadingLevel.HEADING_1 }),
new Paragraph({ text: `Date: ${date}` }),
new Paragraph({ text: `Attendees: ${attendees.join(', ')}` }),
new Paragraph({ text: "Agenda", heading: HeadingLevel.HEADING_2 }),
// ... agenda items
new Paragraph({ text: "Action Items", heading: HeadingLevel.HEADING_2 }),
// ... action items table
]
}]
});
邮件合并:
// Template: Dear {firstName} {lastName}, ...
contacts.forEach(contact => {
generateFromTemplate('letter-template.docx', contact, `letter-${contact.id}.docx`);
});
依赖项
安装所需的软件包:
npm install docx docxtemplater pizzip
高级功能的可选依赖项:
npm install docx-templates # Alternative templating
npm install officegen # Legacy support
错误处理
- 模板错误: 处理前验证模板结构
- 缺少数据: 为可选模板字段提供默认值
- 图像加载: 嵌入前检查图像文件是否存在
- 文件权限: 妥善处理写入权限错误
- 内存问题: 对于大型文档,如果支持,请考虑使用流式处理
- 编码: 确保国际字符使用正确的 UTF-8 编码
性能提示
- 在多个文档之间复用样式定义
- 为批量操作预加载模板
- 对超大型文档使用流式处理
- 嵌入前压缩图像
- 批量执行文件系统操作
- 尽可能缓存已编译的模板
高级功能
目录:
new TableOfContents("Table of Contents", {
hyperlink: true,
headingStyleRange: "1-3"
});
条件部分:
// In template: {#showSection}Content{/showSection}
doc.setData({ showSection: condition ? {...} : false });
自定义编号:
new Paragraph({
text: "Numbered item",
numbering: {
reference: "custom-numbering",
level: 0
}
});
评论
支持 Markdown