DOCX
@office-open/docx
使用声明式 TypeScript API 生成、解析和修补 .docx 文档
安装
pnpm add @office-open/docx
npm install @office-open/docx
yarn add @office-open/docx
bun add @office-open/docx
快速开始
{
"sections": [
{
"children": [{ "paragraph": { "children": ["Hello World"] } }]
}
]
}
import { generateDocument } from "@office-open/docx";
const buffer = await generateDocument({
sections: [
{
children: [{ paragraph: { children: ["Hello World"] } }],
},
],
});
主要组件
| 组件 | 说明 |
|---|---|
sections | 文档根容器,包含节和属性 |
paragraph | 文本段落,支持格式化、对齐和间距 |
text runs | 内联文本,支持字体、大小、颜色和样式 |
table with rows and cells | 结构化表格,支持合并单元格和边框 |
image | 嵌入图片,支持变换和定位 |
chart | 柱状图、折线图、饼图、面积图和散点图 |
smartArt | 预定义 SmartArt 图示 |
headers / footers | 节页眉和页脚 |
footnoteReference, endnoteReference | 脚注和尾注 |
tableOfContents | 自动生成的目录 |
bookmark | 内部书签和交叉引用 |
math | 数学公式(Office MathML / OMML) |
styles | 声明式样式定义 |
hyperlink | 外部和内部超链接 |
comment, commentReference | 文档批注,支持作者和日期跟踪 |
textbox | 浮动文本框 |
checkBox | 表单复选框 |
sdt | 结构化文档标签(SDT) |
insertion / deletion | 修订跟踪 — 插入和删除 |
numbering | 编号和项目符号列表,支持多级 |
symbol / pageBreak 等 | 特殊字符、分页符和分栏符 |
section properties | 页面大小、边距、方向、分栏和页面边框 |
补丁
通过替换 {{占位符}} 标记修改现有 .docx 模板:
import { patchDocument } from "@office-open/docx";
const result = await patchDocument({
outputType: "nodebuffer",
data: templateBuffer,
placeholders: {
name: { type: "paragraph", children: [{ text: "John Doe" }] },
},
});
详见页面。
导出格式
每个异步方法都有对应的同步版本(如 generateDocumentSync)。完整列表见页面。
| 方法 | 返回值 | 适用场景 |
|---|---|---|
generateDocument(opts) | Buffer | Node.js 文件 I/O |
generateDocument(opts, { type: "blob" }) | Blob | 浏览器下载 |
generateDocument(opts, { type: "base64" }) | string | Data URL、API 载荷 |
generateDocument(opts, { type: "string" }) | string | 调试、检查 |
generateDocumentStream(opts) | ReadableStream<Uint8Array> | 流式传输大文件 |