DOCX

@office-open/docx

使用声明式 TypeScript API 生成、解析和修补 .docx 文档

安装

pnpm add @office-open/docx

快速开始

{
  "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)BufferNode.js 文件 I/O
generateDocument(opts, { type: "blob" })Blob浏览器下载
generateDocument(opts, { type: "base64" })stringData URL、API 载荷
generateDocument(opts, { type: "string" })string调试、检查
generateDocumentStream(opts)ReadableStream<Uint8Array>流式传输大文件
Copyright © 2026