科研技能库/DOCX 官方技能
科研效率
未发现用户侧风险

DOCX 官方技能

用户可能要求您创建、编辑或分析 .docx 文件的内容。.docx 文件本质上是一个包含 XML 文件和其他资源的 ZIP 存档,您可以读取或编辑。针对不同任务,您有多种工具和工作流可用。

文件预览

59 个文件
ooxml
schemas
ecma
fouth-edition
ISO-IEC29500-4_2016
mce
microsoft
scripts
validation
scripts
templates
SKILL.md
10.4 KB · 可预览
---
name: docx-official
description: "A user may ask you to create, edit, or analyze the contents of a .docx file. A .docx file is essentially a ZIP archive containing XML files and other resources that you can read or edit. You have different tools and workflows available for different tasks."
risk: unknown
source: community
date_added: "2026-02-27"
---

# DOCX creation, editing, and analysis

## Overview

A user may ask you to create, edit, or analyze the contents of a .docx file. A .docx file is essentially a ZIP archive containing XML files and other resources that you can read or edit. You have different tools and workflows available for different tasks.

## Workflow Decision Tree

### Reading/Analyzing Content
Use "Text extraction" or "Raw XML access" sections below

### Creating New Document
Use "Creating a new Word document" workflow

### Editing Existing Document
- **Your own document + simple changes**
  Use "Basic OOXML editing" workflow

- **Someone else's document**
  Use **"Redlining workflow"** (recommended default)

- **Legal, academic, business, or government docs**
  Use **"Redlining workflow"** (required)

## Reading and analyzing content

### Text extraction
If you just need to read the text contents of a document, you should convert the document to markdown using pandoc. Pandoc provides excellent support for preserving document structure and can show tracked changes:

```bash
# Convert document to markdown with tracked changes
pandoc --track-changes=all path-to-file.docx -o output.md
# Options: --track-changes=accept/reject/all
```

### Raw XML access
You need raw XML access for: comments, complex formatting, document structure, embedded media, and metadata. For any of these features, you'll need to unpack a document and read its raw XML contents.

#### Unpacking a file
`python ooxml/scripts/unpack.py <office_file> <output_directory>`

#### Key file structures
* `word/document.xml` - Main document contents
* `word/comments.xml` - Comments referenced in document.xml
* `word/media/` - Embedded images and media files
* Tracked changes use `<w:ins>` (insertions) and `<w:del>` (deletions) tags

## Creating a new Word document

When creating a new Word document from scratch, use **docx-js**, which allows you to create Word documents using JavaScript/TypeScript.

### Workflow
1. **MANDATORY - READ ENTIRE FILE**: Read [`docx-js.md`](docx-js.md) (~500 lines) completely from start to finish. **NEVER set any range limits when reading this file.** Read the full file content for detailed syntax, critical formatting rules, and best practices before proceeding with document creation.
2. Create a JavaScript/TypeScript file using Document, Paragraph, TextRun components (You can assume all dependencies are installed, but if not, refer to the dependencies section below)
3. Export as .docx using Packer.toBuffer()

## Editing an existing Word document

When editing an existing Word document, use the **Document library** (a Python library for OOXML manipulation). The library automatically handles infrastructure setup and provides methods for document manipulation. For complex scenarios, you can access the underlying DOM directly through the library.

### Workflow
1. **MANDATORY - READ ENTIRE FILE**: Read [`ooxml.md`](ooxml.md) (~600 lines) completely from start to finish. **NEVER set any range limits when reading this file.** Read the full file content for the Document library API and XML patterns for directly editing document files.
2. Unpack the document: `python ooxml/scripts/unpack.py <office_file> <output_directory>`
3. Create and run a Python script using the Document library (see "Document Library" section in ooxml.md)
4. Pack the final document: `python ooxml/scripts/pack.py <input_directory> <office_file>`

The Document library provides both high-level methods for common operations and direct DOM access for complex scenarios.

## Redlining workflow for document review

This workflow allows you to plan comprehensive tracked changes using markdown before implementing them in OOXML. **CRITICAL**: For complete tracked changes, you must implement ALL changes systematically.

**Batching Strategy**: Group related changes into batches of 3-10 changes. This makes debugging manageable while maintaining efficiency. Test each batch before moving to the next.

**Principle: Minimal, Precise Edits**
When implementing tracked changes, only mark text that actually changes. Repeating unchanged text makes edits harder to review and appears unprofessional. Break replacements into: [unchanged text] + [deletion] + [insertion] + [unchanged text]. Preserve the original run's RSID for unchanged text by extracting the `<w:r>` element from the original and reusing it.

Example - Changing "30 days" to "60 days" in a sentence:
```python
# BAD - Replaces entire sentence
'<w:del><w:r><w:delText>The term is 30 days.</w:delText></w:r></w:del><w:ins><w:r><w:t>The term is 60 days.</w:t></w:r></w:ins>'

# GOOD - Only marks what changed, preserves original <w:r> for unchanged text
'<w:r w:rsidR="00AB12CD"><w:t>The term is </w:t></w:r><w:del><w:r><w:delText>30</w:delText></w:r></w:del><w:ins><w:r><w:t>60</w:t></w:r></w:ins><w:r w:rsidR="00AB12CD"><w:t> days.</w:t></w:r>'
```

### Tracked changes workflow

1. **Get markdown representation**: Convert document to markdown with tracked changes preserved:
   ```bash
   pandoc --track-changes=all path-to-file.docx -o current.md
   ```

2. **Identify and group changes**: Review the document and identify ALL changes needed, organizing them into logical batches:

   **Location methods** (for finding changes in XML):
   - Section/heading numbers (e.g., "Section 3.2", "Article IV")
   - Paragraph identifiers if numbered
   - Grep patterns with unique surrounding text
   - Document structure (e.g., "first paragraph", "signature block")
   - **DO NOT use markdown line numbers** - they don't map to XML structure

   **Batch organization** (group 3-10 related changes per batch):
   - By section: "Batch 1: Section 2 amendments", "Batch 2: Section 5 updates"
   - By type: "Batch 1: Date corrections", "Batch 2: Party name changes"
   - By complexity: Start with simple text replacements, then tackle complex structural changes
   - Sequential: "Batch 1: Pages 1-3", "Batch 2: Pages 4-6"

3. **Read documentation and unpack**:
   - **MANDATORY - READ ENTIRE FILE**: Read [`ooxml.md`](ooxml.md) (~600 lines) completely from start to finish. **NEVER set any range limits when reading this file.** Pay special attention to the "Document Library" and "Tracked Change Patterns" sections.
   - **Unpack the document**: `python ooxml/scripts/unpack.py <file.docx> <dir>`
   - **Note the suggested RSID**: The unpack script will suggest an RSID to use for your tracked changes. Copy this RSID for use in step 4b.

4. **Implement changes in batches**: Group changes logically (by section, by type, or by proximity) and implement them together in a single script. This approach:
   - Makes debugging easier (smaller batch = easier to isolate errors)
   - Allows incremental progress
   - Maintains efficiency (batch size of 3-10 changes works well)

   **Suggested batch groupings:**
   - By document section (e.g., "Section 3 changes", "Definitions", "Termination clause")
   - By change type (e.g., "Date changes", "Party name updates", "Legal term replacements")
   - By proximity (e.g., "Changes on pages 1-3", "Changes in first half of document")

   For each batch of related changes:

   **a. Map text to XML**: Grep for text in `word/document.xml` to verify how text is split across `<w:r>` elements.

   **b. Create and run script**: Use `get_node` to find nodes, implement changes, then `doc.save()`. See **"Document Library"** section in ooxml.md for patterns.

   **Note**: Always grep `word/document.xml` immediately before writing a script to get current line numbers and verify text content. Line numbers change after each script run.

5. **Pack the document**: After all batches are complete, convert the unpacked directory back to .docx:
   ```bash
   python ooxml/scripts/pack.py unpacked reviewed-document.docx
   ```

6. **Final verification**: Do a comprehensive check of the complete document:
   - Convert final document to markdown:
     ```bash
     pandoc --track-changes=all reviewed-document.docx -o verification.md
     ```
   - Verify ALL changes were applied correctly:
     ```bash
     grep "original phrase" verification.md  # Should NOT find it
     grep "replacement phrase" verification.md  # Should find it
     ```
   - Check that no unintended changes were introduced


## Converting Documents to Images

To visually analyze Word documents, convert them to images using a two-step process:

1. **Convert DOCX to PDF**:
   ```bash
   soffice --headless --convert-to pdf document.docx
   ```

2. **Convert PDF pages to JPEG images**:
   ```bash
   pdftoppm -jpeg -r 150 document.pdf page
   ```
   This creates files like `page-1.jpg`, `page-2.jpg`, etc.

Options:
- `-r 150`: Sets resolution to 150 DPI (adjust for quality/size balance)
- `-jpeg`: Output JPEG format (use `-png` for PNG if preferred)
- `-f N`: First page to convert (e.g., `-f 2` starts from page 2)
- `-l N`: Last page to convert (e.g., `-l 5` stops at page 5)
- `page`: Prefix for output files

Example for specific range:
```bash
pdftoppm -jpeg -r 150 -f 2 -l 5 document.pdf page  # Converts only pages 2-5
```

## Code Style Guidelines
**IMPORTANT**: When generating code for DOCX operations:
- Write concise code
- Avoid verbose variable names and redundant operations
- Avoid unnecessary print statements

## Dependencies

Required dependencies (install if not available):

- **pandoc**: `sudo apt-get install pandoc` (for text extraction)
- **docx**: `npm install -g docx` (for creating new documents)
- **LibreOffice**: `sudo apt-get install libreoffice` (for PDF conversion)
- **Poppler**: `sudo apt-get install poppler-utils` (for pdftoppm to convert PDF to images)
- **defusedxml**: `pip install defusedxml` (for secure XML parsing)

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

SKILL.md

元数据
namedocx-official
description用户可能要求您创建、编辑或分析 .docx 文件的内容。.docx 文件本质上是一个包含 XML 文件和其他资源的 ZIP 存档,您可以读取或编辑。针对不同任务,您有多种工具和工作流可用。
riskunknown
sourcecommunity
date_added2026-02-27

DOCX 创建、编辑与分析

概述

用户可能要求您创建、编辑或分析 .docx 文件的内容。.docx 文件本质上是一个包含 XML 文件和其他资源的 ZIP 存档,您可以读取或编辑。针对不同任务,您有多种工具和工作流可用。

工作流决策树

读取/分析内容

使用下方“文本提取”或“原始 XML 访问”部分

创建新文档

使用“创建新 Word 文档”工作流

编辑现有文档

  • 您自己的文档 + 简单更改 使用“基础 OOXML 编辑”工作流

  • 他人的文档 使用 "修订工作流" (推荐默认)

  • 法律、学术、商业或政府文档 使用 "修订工作流" (必须)

读取和分析内容

文本提取

如果您只需要读取文档的文本内容,应使用 pandoc 将文档转换为 markdown。Pandoc 在保留文档结构方面表现出色,并可显示修订信息:

bash
# Convert document to markdown with tracked changes
pandoc --track-changes=all path-to-file.docx -o output.md
# Options: --track-changes=accept/reject/all

原始 XML 访问

对于以下情况,您需要原始 XML 访问:批注、复杂格式、文档结构、嵌入媒体和元数据。对于这些功能,您需要解包文档并读取其原始 XML 内容。

解包文件

python ooxml/scripts/unpack.py <office_file> <output_directory>

关键文件结构

  • word/document.xml - 主文档内容
  • word/comments.xml - document.xml 中引用的批注
  • word/media/ - 嵌入的图像和媒体文件
  • 修订使用 <w:ins>(插入)和 <w:del>(删除)标签

创建新 Word 文档

从头创建新 Word 文档时,请使用 docx-js,它允许您使用 JavaScript/TypeScript 创建 Word 文档。

工作流

  1. 必须 - 阅读完整文件:从头到尾阅读 docx-js.md(约 500 行)。设置范围限制时切勿设置。 在创建文档前阅读完整文件内容,了解详细语法、关键格式规则和最佳实践。
  2. 使用 Document、Paragraph、TextRun 组件创建 JavaScript/TypeScript 文件(您可假设所有依赖项已安装,若未安装,请参考下方的依赖项部分)
  3. 使用 Packer.toBuffer() 导出为 .docx

编辑现有 Word 文档

编辑现有 Word 文档时,请使用 Document 库(一个用于 OOXML 操作的 Python 库)。该库自动处理基础设施设置,并提供文档操作方法。对于复杂场景,您可以通过该库直接访问底层 DOM。

工作流

  1. 必须 - 阅读完整文件:从头到尾阅读 ooxml.md(约 600 行)。设置范围限制时切勿设置。 阅读完整文件内容,了解 Document 库 API 和直接编辑文档文件的 XML 模式。
  2. 解包文档:python ooxml/scripts/unpack.py <office_file> <output_directory>
  3. 创建并运行 Python 脚本,使用 Document 库(参见 ooxml.md 中的“Document Library”部分)
  4. 打包最终文档:python ooxml/scripts/pack.py <input_directory> <office_file>

Document 库提供常见操作的高级方法和复杂场景的直接 DOM 访问。

文档审阅的修订工作流

此工作流允许您使用 markdown 规划全面的修订,然后在 OOXML 中实现。关键:对于完整的修订,您必须系统地实现所有更改。

批处理策略:将相关更改分组为 3-10 个更改的批次。这样便于调试,同时保持效率。在移至下一批次之前测试每个批次。

原则:最小精确编辑 实现修订时,仅标记实际更改的文本。重复未更改的文本会使编辑难以审阅且显得不专业。将替换分解为:[未更改文本] + [删除] + [插入] + [未更改文本]。通过从原始文档中提取 <w:r> 元素并重用,保留未更改文本的原始 RSID。

示例 - 将句中的“30 天”更改为“60 天”:

python
# BAD - Replaces entire sentence
'<w:del><w:r><w:delText>The term is 30 days.</w:delText></w:r></w:del><w:ins><w:r><w:t>The term is 60 days.</w:t></w:r></w:ins>'

# GOOD - Only marks what changed, preserves original <w:r> for unchanged text
'<w:r w:rsidR="00AB12CD"><w:t>The term is </w:t></w:r><w:del><w:r><w:delText>30</w:delText></w:r></w:del><w:ins><w:r><w:t>60</w:t></w:r></w:ins><w:r w:rsidR="00AB12CD"><w:t> days.</w:t></w:r>'

修订工作流

  1. 获取 markdown 表示:将文档转换为保留修订的 markdown:

    bash
    pandoc --track-changes=all path-to-file.docx -o current.md
  2. 识别和分组更改:审阅文档并识别所有需要更改的内容,将其组织成逻辑批次:

    定位方法(用于在 XML 中查找更改):

    • 章节/标题编号(例如,“第 3.2 节”、“Article IV”)
    • 段落标识符(如果已编号)
    • 使用唯一周围文本的 Grep 模式
    • 文档结构(例如,“第一个段落”、“签名块”)
    • 切勿使用 markdown 行号 - 它们不映射到 XML 结构

    批次组织(每个批次 3-10 个相关更改):

    • 按章节:“批次 1:第 2 节修订”,“批次 2:第 5 节更新”
    • 按类型:“批次 1:日期更正”,“批次 2:方名更改”
    • 按复杂性:从简单的文本替换开始,然后处理复杂的结构更改
    • 顺序:“批次 1:第 1-3 页”,“批次 2:第 4-6 页”
  3. 阅读文档和解包:

    • 必须 - 阅读完整文件:从头到尾阅读 ooxml.md(约 600 行)。设置范围限制时切勿设置。 特别注意“Document Library”和“Tracked Change Patterns”部分。
    • 解包文档:python ooxml/scripts/unpack.py <file.docx> <dir>
    • 记录建议的 RSID:解包脚本将建议一个 RSID 用于您的修订。复制此 RSID 以备步骤 4b 使用。
  4. 批量实现更改:将更改按逻辑分组(按章节、类型或接近度),并在单个脚本中一起实现。这种方法:

    • 使调试更容易(批次越小,隔离错误越容易)
    • 允许增量进度
    • 保持效率(批次大小 3-10 个更改效果良好)

    建议的批次分组:

    • 按文档章节(例如,“第 3 节更改”、“定义”、“终止条款”)
    • 按更改类型(例如,“日期更改”、“方名更新”、“法律术语替换”)
    • 按接近度(例如,“第 1-3 页的更改”、“文档前半部分的更改”)

    对于每个相关更改批次:

    a. 将文本映射到 XML:在 word/document.xml 中搜索文本,验证文本如何跨 <w:r> 元素分割。

    b. 创建并运行脚本:使用 get_node 查找节点,实现更改,然后 doc.save()。有关模式,请参见 ooxml.md 中的 “Document Library” 部分。

    注意:在编写脚本之前,始终立即搜索 word/document.xml 以获取当前行号并验证文本内容。每次脚本运行后行号都会变化。

  5. 打包文档:所有批次完成后,将解包目录转换回 .docx:

    bash
    python ooxml/scripts/pack.py unpacked reviewed-document.docx
  6. 最终验证:对完整文档进行全面检查:

    • 将最终文档转换为 markdown:
      bash
      pandoc --track-changes=all reviewed-document.docx -o verification.md
    • 验证所有更改均已正确应用:
      bash
      grep "original phrase" verification.md  # 不应找到
      grep "replacement phrase" verification.md  # 应找到
    • 检查是否引入了意外更改

将文档转换为图像

要以视觉方式分析 Word 文档,可通过两步过程将其转换为图像:

  1. 将 DOCX 转换为 PDF:

    bash
    soffice --headless --convert-to pdf document.docx
  2. 将 PDF 页面转换为 JPEG 图像:

    bash
    pdftoppm -jpeg -r 150 document.pdf page

    这将创建类似 page-1.jpg、page-2.jpg 等的文件。

选项:

  • -r 150:设置分辨率为 150 DPI(根据需要调整质量/大小平衡)
  • -jpeg:输出 JPEG 格式(如需 PNG 可使用 -png)
  • -f N:要转换的第一页(例如,-f 2 从第 2 页开始)
  • -l N:要转换的最后一页(例如,-l 5 在第 5 页停止)
  • page:输出文件前缀

特定范围示例:

bash
pdftoppm -jpeg -r 150 -f 2 -l 5 document.pdf page  # 仅转换第 2-5 页

代码风格指南

重要:为 DOCX 操作生成代码时:

  • 编写简洁的代码
  • 避免冗长的变量名和冗余操作
  • 避免不必要的打印语句

依赖项

所需依赖项(如果不可用,请安装):

  • pandoc:sudo apt-get install pandoc(用于文本提取)
  • docx:npm install -g docx(用于创建新文档)
  • LibreOffice:sudo apt-get install libreoffice(用于 PDF 转换)
  • Poppler:sudo apt-get install poppler-utils(用于 pdftoppm 将 PDF 转换为图像)
  • defusedxml:pip install defusedxml(用于安全的 XML 解析)

何时使用

此技能适用于执行概述中描述的工作流或操作。

限制

  • 仅在任务明确匹配上述范围时使用此技能。
  • 请勿将输出视为环境特定验证、测试或专家评审的替代。
  • 如果缺少所需的输入、权限、安全边界或成功标准,请停止并寻求澄清。