DOCX

快速开始

使用 @office-open/docx 在 5 分钟内创建你的第一个 .docx 文档

只需三步即可从零创建一个 Word 文档:定义内容、构建文档、导出。

第一步 — 安装

pnpm add @office-open/docx

第二步 — 创建文档

import { generateDocument } from "@office-open/docx";

const doc = {
  sections: [
    {
      children: [
        // 标题段落
        {
          paragraph: {
            heading: "Heading1",
            children: [{ text: "My First Document", bold: true, size: 32 }],
          },
        },

        // 正文段落
        {
          paragraph: {
            children: [
              "This is a paragraph with ",
              { text: "bold", bold: true },
              " and ",
              { text: "italic", italic: true },
              " text.",
            ],
          },
        },
      ],
    },
  ],
};

或使用 JSON:

{
  "sections": [
    {
      "children": [
        {
          "paragraph": {
            "heading": "Heading1",
            "children": [{ "text": "My First Document", "bold": true, "size": 16 }]
          }
        },
        {
          "paragraph": {
            "children": [
              "This is a paragraph with ",
              { "text": "bold", "bold": true },
              " and ",
              { "text": "italic", "italic": true },
              " text."
            ]
          }
        }
      ]
    }
  ]
}

第三步 — 导出

// Node.js — 写入文件
import { writeFileSync } from "node:fs";
import { generateDocument } from "@office-open/docx";

const buffer = await generateDocument(doc);
writeFileSync("output.docx", buffer);
// 浏览器 — 下载文件
import { generateDocument } from "@office-open/docx";

const blob = await generateDocument(doc, { type: "blob" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "output.docx";
a.click();

输出格式

generateDocument() 支持多种输出格式。每个异步方法都有对应的同步版本(如 generateDocumentSync)。完整列表见页面。

方法返回值适用场景
generateDocument(opts)BufferNode.js 文件 I/O
generateDocument(opts, { type: "blob" })Blob浏览器下载
generateDocument(opts, { type: "base64" })stringData URL、API 载荷
generateDocumentSync(opts)Buffer同步生成
generateDocumentStream(opts)ReadableStream<Uint8Array>流式传输大文件
Copyright © 2026