DOCX
@office-open/docx
使用声明式 TypeScript API 生成 .docx 文档
安装
pnpm add @office-open/docx
快速开始
import { Document, Packer, Paragraph, TextRun } from "@office-open/docx";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [new TextRun("Hello World")],
}),
],
},
],
});
const buffer = await Packer.toBuffer(doc);
主要组件
| 组件 | 说明 |
|---|---|
Document | 文档根容器,包含节和属性 |
Paragraph | 文本段落,支持格式化、对齐和间距 |
TextRun | 内联文本,支持字体、大小、颜色和样式 |
Table, TableRow, TableCell | 结构化表格,支持合并单元格和边框 |
ImageRun | 嵌入图片,支持变换和定位 |
ChartRun | 柱状图、折线图、饼图、面积图和散点图 |
SmartArtRun | 预定义 SmartArt 图示 |
Header, Footer | 节页眉和页脚 |
FootnoteReferenceRun | 脚注和尾注 |
TableOfContents | 自动生成的目录 |
Bookmark | 内部书签和交叉引用 |
Math, MathRun | 数学公式 |
Styles | 声明式样式定义 |
导出格式
| 方法 | 返回值 | 适用场景 |
|---|---|---|
Packer.toBuffer(doc) | Uint8Array | Node.js 文件 I/O |
Packer.toBlob(doc) | Blob | 浏览器下载 |
Packer.toBase64String(doc) | string | Data URL、API 载荷 |
Packer.toString(doc) | string | 调试、检查 |
Packer.toStream(doc) | ReadableStream | 流式传输大文件 |