DOCX

快速开始

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

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

第一步 — 安装

pnpm add @office-open/docx

第二步 — 创建文档

import { Document, Packer, Paragraph, TextRun } from "@office-open/docx";

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

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

第三步 — 导出

// Node.js — 写入文件
import { writeFileSync } from "node:fs";

const buffer = await Packer.toBuffer(doc);
writeFileSync("output.docx", buffer);
// 浏览器 — 下载文件
const blob = await Packer.toBlob(doc);
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "output.docx";
a.click();

输出格式

Packer 类支持多种输出格式:

方法返回值适用场景
Packer.toBuffer(doc)Uint8ArrayNode.js 文件 I/O
Packer.toBlob(doc)Blob浏览器下载
Packer.toBase64String(doc)stringData URL、API 载荷
Packer.toString(doc)string调试、检查
Packer.toStream(doc)ReadableStream流式传输大文件
Copyright © 2026