docx 中文教程

1. 项目概述

docx 是一个功能强大的 JavaScript 库,用于创建和修改 Microsoft Word 文档。它提供了简单易用的 API,允许开发者在 Node.js 或浏览器环境中生成专业的 Word 文档。

  • 官方 GitHub 仓库https://github.com/dolanmiu/docx
  • 适用环境:Node.js、Web 浏览器
  • 主要特点:创建 Word 文档、添加段落、表格、图片、样式设置等

2. 核心功能

2.1 基本功能

  • 文档创建:生成新的 Word 文档
  • 段落处理:添加和格式化段落
  • 文本样式:设置字体、大小、颜色、粗体、斜体等
  • 表格操作:创建表格、设置单元格样式、合并单元格等
  • 图片插入:添加图片到文档中
  • 页面设置:设置页面大小、边距、方向等
  • 页眉页脚:添加和设置页眉页脚

2.2 高级功能

  • 文档结构:创建章节、标题、目录等
  • 样式管理:定义和应用自定义样式
  • 列表功能:创建有序和无序列表
  • 超链接:添加内部和外部超链接
  • 书签:创建和使用书签
  • 注释:添加脚注和尾注
  • 表格 of contents:生成目录
  • 文档保护:设置文档密码和权限

3. 安装与设置

3.1 在 Node.js 环境中安装

npm install docx

3.2 在浏览器中使用

可以通过 CDN 直接引入:

<script src="https://unpkg.com/docx@latest/build/index.js"></script>

或者使用打包工具如 Webpack、Rollup 等引入。

4. 基本使用示例

4.1 创建简单文档

// 导入库(Node.js 环境)
const { Document, Packer, Paragraph, TextRun } = require('docx');

// 创建新文档
const doc = new Document({});

// 添加标题
const title = new Paragraph({
  children: [
    new TextRun({
      text: 'Hello World!',
      bold: true,
      size: 32,
    }),
  ],
  alignment: 'center',
});

doc.addParagraph(title);

// 添加内容
const content = new Paragraph({
  children: [
    new TextRun({
      text: '这是使用 docx 库创建的文档。',
      size: 20,
    }),
  ],
});

doc.addParagraph(content);

// 保存文档(Node.js 环境)
Packer.toBuffer(doc).then((buffer) => {
  require('fs').writeFileSync('hello-world.docx', buffer);
  console.log('文档创建成功!');
});

4.2 在浏览器中下载文档

// 导入库(浏览器环境)
// 假设已经通过 CDN 引入了 docx 库

// 创建新文档
const doc = new docx.Document({});

// 添加内容
const paragraph = new docx.Paragraph({
  children: [
    new docx.TextRun({
      text: 'Hello World!',
      bold: true,
    }),
  ],
});

doc.addParagraph(paragraph);

// 生成并下载文档
docx.Packer.toBlob(doc).then((blob) => {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'hello-world.docx';
  a.click();
  URL.revokeObjectURL(url);
});

4.3 添加表格

const { Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell } = require('docx');

const doc = new Document({});

// 添加表格标题
doc.addParagraph(new Paragraph({
  children: [new TextRun({ text: '产品列表', bold: true, size: 24 })],
  alignment: 'center',
}));

// 创建表格
const table = new Table({
  rows: [
    // 表头
    new TableRow({
      children: [
        new TableCell({
          children: [new Paragraph('产品名称')],
          shading: { fill: '#E0E0E0' },
        }),
        new TableCell({
          children: [new Paragraph('价格')],
          shading: { fill: '#E0E0E0' },
        }),
        new TableCell({
          children: [new Paragraph('库存')],
          shading: { fill: '#E0E0E0' },
        }),
      ],
    }),
    // 数据行
    new TableRow({
      children: [
        new TableCell({ children: [new Paragraph('产品 A')] }),
        new TableCell({ children: [new Paragraph('$10.00')] }),
        new TableCell({ children: [new Paragraph('100')] }),
      ],
    }),
    new TableRow({
      children: [
        new TableCell({ children: [new Paragraph('产品 B')] }),
        new TableCell({ children: [new Paragraph('$20.00')] }),
        new TableCell({ children: [new Paragraph('50')] }),
      ],
    }),
    new TableRow({
      children: [
        new TableCell({ children: [new Paragraph('产品 C')] }),
        new TableCell({ children: [new Paragraph('$30.00')] }),
        new TableCell({ children: [new Paragraph('75')] }),
      ],
    }),
  ],
});

// 添加表格到文档
doc.addTable(table);

// 保存文档
Packer.toBuffer(doc).then((buffer) => {
  require('fs').writeFileSync('table-example.docx', buffer);
  console.log('文档创建成功!');
});

4.4 添加图片

const { Document, Packer, Paragraph, ImageRun } = require('docx');
const fs = require('fs');

const doc = new Document({});

// 添加图片标题
doc.addParagraph(new Paragraph({
  children: [new TextRun({ text: '图片示例', bold: true, size: 24 })],
  alignment: 'center',
}));

// 读取图片文件
const imageBuffer = fs.readFileSync('path/to/image.png');

// 创建图片
const image = new ImageRun({
  data: imageBuffer,
  transformation: {
    width: 500,
    height: 300,
  },
});

// 添加图片到文档
doc.addParagraph(new Paragraph({ children: [image] }));

// 保存文档
Packer.toBuffer(doc).then((buffer) => {
  fs.writeFileSync('image-example.docx', buffer);
  console.log('文档创建成功!');
});

5. 高级用法

5.1 使用样式

const { Document, Packer, Paragraph, TextRun, HeadingLevel } = require('docx');

const doc = new Document({
  styles: {
    paragraphStyles: [
      {
        id: 'Heading1',
        name: 'Heading 1',
        basedOn: 'Normal',
        next: 'Normal',
        quickFormat: true,
        runs: [
          {
            size: 32,
            bold: true,
            color: '333333',
          },
        ],
        paragraph: {
          spacing: {
            after: 240,
            before: 0,
          },
        },
      },
      {
        id: 'Heading2',
        name: 'Heading 2',
        basedOn: 'Normal',
        next: 'Normal',
        quickFormat: true,
        runs: [
          {
            size: 24,
            bold: true,
            color: '666666',
          },
        ],
        paragraph: {
          spacing: {
            after: 180,
            before: 0,
          },
        },
      },
    ],
  },
});

// 添加标题(使用自定义样式)
doc.addParagraph(
  new Paragraph({
    text: '第一章 介绍',
    heading: HeadingLevel.HEADING_1,
  })
);

// 添加子标题
doc.addParagraph(
  new Paragraph({
    text: '1.1 什么是 docx 库',
    heading: HeadingLevel.HEADING_2,
  })
);

// 添加内容
doc.addParagraph(
  new Paragraph({
    children: [
      new TextRun({
        text: 'docx 是一个功能强大的 JavaScript 库,用于创建和修改 Microsoft Word 文档。',
      }),
    ],
  })
);

// 保存文档
Packer.toBuffer(doc).then((buffer) => {
  require('fs').writeFileSync('styles-example.docx', buffer);
  console.log('文档创建成功!');
});

5.2 创建列表

const { Document, Packer, Paragraph, TextRun } = require('docx');

const doc = new Document({});

// 添加标题
doc.addParagraph(
  new Paragraph({
    children: [new TextRun({ text: '任务列表', bold: true, size: 24 })],
    alignment: 'center',
  })
);

// 添加有序列表
const orderedListItems = ['完成项目规划', '实现核心功能', '编写测试用例', '部署上线'];

orderedListItems.forEach((item, index) => {
  doc.addParagraph(
    new Paragraph({
      children: [new TextRun({ text: item })],
      numbering: {
        reference: 'custom-numbering',
        level: 0,
      },
    })
  );
});

// 添加无序列表
const unorderedListItems = ['学习 JavaScript', '掌握 Node.js', '熟悉前端框架', '了解后端开发'];

unorderedListItems.forEach((item) => {
  doc.addParagraph(
    new Paragraph({
      children: [new TextRun({ text: item })],
      bullet: { level: 0 },
    })
  );
});

// 保存文档
Packer.toBuffer(doc).then((buffer) => {
  require('fs').writeFileSync('list-example.docx', buffer);
  console.log('文档创建成功!');
});

5.3 设置页面属性

const { Document, Packer, Paragraph, TextRun, PageSize, PageMargins, Orientation } = require('docx');

const doc = new Document({
  sections: [
    {
      properties: {
        page: {
          size: PageSize.A4,
          margins: new PageMargins({
            top: 720,
            right: 720,
            bottom: 720,
            left: 720,
            header: 360,
            footer: 360,
            gutter: 0,
          }),
          orientation: Orientation.PORTRAIT,
        },
        header: {
          children: [
            new Paragraph({
              children: [new TextRun({ text: '文档页眉', size: 20 })],
              alignment: 'center',
            }),
          ],
        },
        footer: {
          children: [
            new Paragraph({
              children: [new TextRun({ text: '文档页脚', size: 20 })],
              alignment: 'center',
            }),
          ],
        },
      },
      children: [
        new Paragraph({
          children: [new TextRun({ text: '页面设置示例', bold: true, size: 24 })],
          alignment: 'center',
        }),
        new Paragraph({
          children: [new TextRun({ text: '这是一个使用自定义页面设置的文档。' })],
        }),
      ],
    },
  ],
});

// 保存文档
Packer.toBuffer(doc).then((buffer) => {
  require('fs').writeFileSync('page-settings-example.docx', buffer);
  console.log('文档创建成功!');
});

6. 实际应用场景

6.1 生成报告

使用 docx 库从数据库或 API 获取数据,生成包含表格、图表和格式化文本的专业报告。

6.2 自动化文档生成

根据用户输入或模板自动生成个性化文档,如合同、发票、简历等。

6.3 教育内容创建

为在线课程生成包含教程内容、练习和答案的 Word 文档。

6.4 企业文档管理

创建和管理企业内部文档,如员工手册、政策文档、培训材料等。

7. 代码优化建议

7.1 模块化设计

将文档生成逻辑拆分为多个模块,提高代码可维护性:

// 文档生成器模块
class DocumentGenerator {
  constructor() {
    this.doc = new Document({});
  }

  addTitle(title) {
    this.doc.addParagraph(
      new Paragraph({
        children: [new TextRun({ text: title, bold: true, size: 32 })],
        alignment: 'center',
      })
    );
    return this;
  }

  addSection(title, content) {
    this.doc.addParagraph(
      new Paragraph({
        text: title,
        heading: HeadingLevel.HEADING_1,
      })
    );
    this.doc.addParagraph(
      new Paragraph({
        children: [new TextRun({ text: content })],
      })
    );
    return this;
  }

  addTable(headers, rows) {
    // 创建表格逻辑
    return this;
  }

  async save(filename) {
    const buffer = await Packer.toBuffer(this.doc);
    require('fs').writeFileSync(filename, buffer);
    console.log(`文档已保存为 ${filename}`);
  }
}

// 使用示例
const generator = new DocumentGenerator();
generator
  .addTitle('项目报告')
  .addSection('项目概述', '本项目旨在...')
  .addSection('项目进度', '目前已完成...')
  .save('project-report.docx');

7.2 错误处理

添加适当的错误处理,提高代码健壮性:

try {
  const doc = new Document({});
  // 操作
  const buffer = await Packer.toBuffer(doc);
  require('fs').writeFileSync('document.docx', buffer);
  console.log('文档创建成功!');
} catch (error) {
  console.error('生成文档时出错:', error);
  // 处理错误
}

7.3 性能优化

对于大型文档,使用异步操作和分批处理:

async function generateLargeDocument(data) {
  const doc = new Document({});
  
  // 分批处理数据
  const batchSize = 100;
  for (let i = 0; i < data.length; i += batchSize) {
    const batch = data.slice(i, i + batchSize);
    
    // 处理当前批次
    for (const item of batch) {
      // 添加内容
    }
    
    // 可选:在批次之间添加延迟,避免内存问题
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  
  const buffer = await Packer.toBuffer(doc);
  require('fs').writeFileSync('large-document.docx', buffer);
  console.log('大型文档创建成功!');
}

8. 总结

docx 是一个功能强大、灵活易用的 JavaScript 库,为开发者提供了在各种环境中创建和修改 Microsoft Word 文档的能力。它的主要优势包括:

  • 跨平台兼容:可在 Node.js、浏览器等多种环境中使用
  • 功能丰富:支持从基本文本到复杂表格、图片的各种元素
  • 易于集成:简单的 API 设计,易于与现有项目集成
  • 高度可定制:支持自定义样式、页面设置、页眉页脚等
  • 活跃维护:持续更新和改进

通过本教程的学习,您应该已经掌握了 docx 的基本用法和一些高级技巧,可以开始在实际项目中应用它来生成 Word 文档了。

9. 参考资源

« 上一篇 pptx.js 中文教程 下一篇 » exceljs 中文教程