跳到主内容
智客 ZICQ

技能库 智客分类:文档办公 docx-manipulation

Docx Manipulation

创建、编辑和操纵 使用 python- docx 程序化的单词文档

5298 安装量

官方网址:skills.sh

技能介绍

先看中文介绍;官方 description 原文单独保留,不改写 SKILL.md。

做什么

创建、编辑和操纵 使用 python- docx 程序化的单词文档

何时用

官方 description 未单独写出 Use when。按规范,代理会在用户任务与这段 description 的关键词匹配时激活本技能。

代理如何加载

按 Agent Skills 渐进披露:启动时只加载 name 与 description(约 100 token);任务匹配后才读入整份 SKILL.md 正文;scripts/、references/、assets/ 仅在需要时再读。 本文件正文结构:DOCX Manipulation Skill、Overview、How to Use、Domain Knowledge、python-docx Fundamentals、Create new document。 其中含规范建议的小节:边界情况。

文件分析

文件分析:这是一份仅含 SKILL.md 的指令型技能,代理激活后整份正文进入上下文。

官方 description(原文)

Create, edit, and manipulate Word documents programmatically using python-docx

DOCX Manipulation SkillOverviewHow to UseDomain Knowledgepython-docx FundamentalsCreate new documentOr open existingDocument StructureAdding ContentAdd heading (level 0-9)Add paragraphAdd styled paragraph

· 许可:MIT

来源分类:skills.sh agent-skill

SKILL.md 与 Agent 调用

官方规范 ↗
name
docx-manipulation
description
Create, edit, and manipulate Word documents programmatically using python-docx
许可
MIT
  1. 发现技能客户端向 Agent 提供名称与描述目录。
  2. 匹配与调用用户指定或任务匹配后,载入 SKILL.md 指令。
  3. 按需加载按步骤读取参考文档、使用脚本与素材。

具体调用语法与可用工具以目标 Agent 客户端为准。 查看调用机制说明 ↗

安装这个技能

Skills CLI ↗

先选择目标 Agent 和安装范围,保留技能包的附属文件,安装后检查客户端能否发现该技能。

交给 Agent 安装

复制安装指令给支持 Agent Skills 的代理,确认其中的目标目录与客户端匹配。

把 Agent Skill「docx-manipulation」安装到我的项目:SKILL.md 原文与官方 description 见 https://zicq.com/zh/skills/skl-7baeb4031040853e-Docx-Manipulation.html
请存为 .cursor/skills/docx-manipulation/SKILL.md 或 .claude/skills/docx-manipulation/SKILL.md,frontmatter 的 name 与 description 保持原样,不要改写。

GitHub 完整包 ↗

终端安装 · Skills CLI

需要 Node.js 与 npx。先查看仓库技能列表,确认实际名称。

npx skills add 'https://github.com/claude-office-skills/skills' --list

npx skills add 'https://github.com/claude-office-skills/skills' --skill 'docx-manipulation'

CLI 会交互选择目标 Agent,默认安装到项目;用户级安装使用 -g。先通过查看命令核对仓库内容,再用 npx skills list 检查已安装技能。

阅读排版

═══════════════════════════════════════════════════════════════════════════════

CLAUDE OFFICE SKILL - Enhanced Metadata v2.0

═══════════════════════════════════════════════════════════════════════════════

Basic Information

name: docx-manipulation description: "Create, edit, and manipulate Word documents programmatically using python-docx" version: "1.0" author: claude-office-skills license: MIT

Categorization

category: document tags:

  • docx
  • word
  • manipulation
  • editing department: All

AI Model Compatibility

models: recommended: - claude-sonnet-4 - claude-opus-4 compatible: - claude-3-5-sonnet - gpt-4 - gpt-4o

MCP Tools Integration

mcp: server: office-mcp tools: - create_docx - extract_text_from_docx - fill_docx_template - merge_docx_files

Skill Capabilities

capabilities:

  • document_creation
  • editing
  • template_handling

Language Support

languages:

  • en
  • zh

DOCX Manipulation Skill

Overview

This skill enables programmatic creation, editing, and manipulation of Microsoft Word (.docx) documents using the python-docx library. Create professional documents with proper formatting, styles, tables, and images without manual editing.

How to Use

  1. Describe what you want to create or modify in a Word document
  2. Provide any source content (text, data, images)
  3. I'll generate python-docx code and execute it

Example prompts:

  • "Create a professional report with title, headings, and a table"
  • "Add a header and footer to this document"
  • "Generate a contract document with placeholders"
  • "Convert this markdown content to a styled Word document"

Domain Knowledge

python-docx Fundamentals

from docx import Document
from docx.shared import Inches, Pt, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE

# Create new document
doc = Document()

# Or open existing
doc = Document('existing.docx')

Document Structure

Document
├── sections (margins, orientation, size)
├── paragraphs (text with formatting)
├── tables (rows, cells, merged cells)
├── pictures (inline images)
└── styles (predefined formatting)

Adding Content

Paragraphs & Headings

# Add heading (level 0-9)
doc.add_heading('Main Title', level=0)
doc.add_heading('Section Title', level=1)

# Add paragraph
para = doc.add_paragraph('Normal text here')

# Add styled paragraph
doc.add_paragraph('Note: Important!', style='Intense Quote')

# Add with inline formatting
para = doc.add_paragraph()
para.add_run('Bold text').bold = True
para.add_run(' and ')
para.add_run('italic text').italic = True

Tables

# Create table
table = doc.add_table(rows=3, cols=3)
table.style = 'Table Grid'

# Add content
table.cell(0, 0).text = 'Header 1'
table.rows[0].cells[1].text = 'Header 2'

# Add row dynamically
row = table.add_row()
row.cells[0].text = 'New data'

# Merge cells
a = table.cell(0, 0)
b = table.cell(0, 2)
a.merge(b)

Images

# Add image with size
doc.add_picture('image.png', width=Inches(4))

# Add to specific paragraph
para = doc.add_paragraph()
run = para.add_run()
run.add_picture('logo.png', width=Inches(1.5))

Formatting

Paragraph Formatting

from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt, Inches

para = doc.add_paragraph('Formatted text')
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
para.paragraph_format.line_spacing = 1.5
para.paragraph_format.space_after = Pt(12)
para.paragraph_format.first_line_indent = Inches(0.5)

Character Formatting

run = para.add_run('Styled text')
run.bold = True
run.italic = True
run.underline = True
run.font.name = 'Arial'
run.font.size = Pt(14)
run.font.color.rgb = RGBColor(0x00, 0x00, 0xFF)  # Blue

Page Setup

from docx.enum.section import WD_ORIENT
from docx.shared import Inches

section = doc.sections[0]
section.page_width = Inches(11)
section.page_height = Inches(8.5)
section.orientation = WD_ORIENT.LANDSCAPE
section.left_margin = Inches(1)
section.right_margin = Inches(1)

Headers & Footers

section = doc.sections[0]

# Header
header = section.header
header.paragraphs[0].text = "Company Name"
header.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER

# Footer with page numbers
footer = section.footer
para = footer.paragraphs[0]
para.text = "Page "
# Add page number field
run = para.add_run()
fldChar1 = OxmlElement('w:fldChar')
fldChar1.set(qn('w:fldCharType'), 'begin')
run._r.append(fldChar1)
# ... (field code for page number)

Styles

# Use built-in styles
doc.add_paragraph('Heading', style='Heading 1')
doc.add_paragraph('Quote', style='Quote')
doc.add_paragraph('List item', style='List Bullet')

# Common styles:
# - 'Normal', 'Heading 1-9', 'Title', 'Subtitle'
# - 'Quote', 'Intense Quote', 'List Bullet', 'List Number'
# - 'Table Grid', 'Light Shading', 'Medium Grid 1'

Best Practices

  1. Structure First: Plan document hierarchy before coding
  2. Use Styles: Consistent formatting via styles, not manual formatting
  3. Save Often: Call doc.save() periodically for large documents
  4. Handle Errors: Check file existence before opening
  5. Clean Up: Remove template placeholders after filling

Common Patterns

Report Template

def create_report(title, sections):
    doc = Document()
    doc.add_heading(title, 0)
    doc.add_paragraph(f'Generated: {datetime.now()}')
    
    for section_title, content in sections.items():
        doc.add_heading(section_title, 1)
        doc.add_paragraph(content)
    
    return doc

Table from Data

def add_data_table(doc, headers, rows):
    table = doc.add_table(rows=1, cols=len(headers))
    table.style = 'Table Grid'
    
    # Headers
    for i, header in enumerate(headers):
        table.rows[0].cells[i].text = header
        table.rows[0].cells[i].paragraphs[0].runs[0].bold = True
    
    # Data rows
    for row_data in rows:
        row = table.add_row()
        for i, value in enumerate(row_data):
            row.cells[i].text = str(value)
    
    return table

Mail Merge Pattern

def fill_template(template_path, replacements):
    doc = Document(template_path)
    
    for para in doc.paragraphs:
        for key, value in replacements.items():
            if f'{{{key}}}' in para.text:
                para.text = para.text.replace(f'{{{key}}}', value)
    
    return doc

Examples

Example 1: Create a Business Letter

from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from datetime import datetime

doc = Document()

# Letterhead
doc.add_paragraph('ACME Corporation')
doc.add_paragraph('123 Business Ave, Suite 100')
doc.add_paragraph('New York, NY 10001')
doc.add_paragraph()

# Date
doc.add_paragraph(datetime.now().strftime('%B %d, %Y'))
doc.add_paragraph()

# Recipient
doc.add_paragraph('Mr. John Smith')
doc.add_paragraph('XYZ Company')
doc.add_paragraph('456 Industry Blvd')
doc.add_paragraph('Chicago, IL 60601')
doc.add_paragraph()

# Salutation
doc.add_paragraph('Dear Mr. Smith,')
doc.add_paragraph()

# Body
body = """We are pleased to inform you that your proposal has been accepted...

[Letter body continues...]

Thank you for your continued partnership."""

for para_text in body.split('\n\n'):
    doc.add_paragraph(para_text)

doc.add_paragraph()
doc.add_paragraph('Sincerely,')
doc.add_paragraph()
doc.add_paragraph()
doc.add_paragraph('Jane Doe')
doc.add_paragraph('CEO, ACME Corporation')

doc.save('business_letter.docx')

Example 2: Create a Report with Table

from docx import Document
from docx.shared import Inches

doc = Document()
doc.add_heading('Q4 Sales Report', 0)

# Executive Summary
doc.add_heading('Executive Summary', 1)
doc.add_paragraph('Q4 2024 showed strong growth across all regions...')

# Sales Table
doc.add_heading('Regional Performance', 1)

table = doc.add_table(rows=1, cols=4)
table.style = 'Medium Grid 1 Accent 1'

headers = ['Region', 'Q3 Sales', 'Q4 Sales', 'Growth']
for i, header in enumerate(headers):
    table.rows[0].cells[i].text = header

data = [
    ['North America', '$1.2M', '$1.5M', '+25%'],
    ['Europe', '$800K', '$950K', '+18%'],
    ['Asia Pacific', '$600K', '$750K', '+25%'],
]

for row_data in data:
    row = table.add_row()
    for i, value in enumerate(row_data):
        row.cells[i].text = value

doc.save('sales_report.docx')

Limitations

  • Cannot execute macros or VBA code
  • Complex templates may lose some formatting
  • Limited support for advanced features (SmartArt, Charts)
  • No direct PDF conversion (use separate tool)
  • Track changes reading is limited

Installation

pip install python-docx

Resources

相关技能

文档办公

Ontology

为结构化的代理内存和可堆肥技能所打入的知识图. 在创建/征服实体(Person, project, Task, Evention, Document)时使用,链接相关对象,强制约束,规划多步动作作为图变,或技能需要共享状态时使用. 触发到"记住","我知道什么","链接X到Y",…

文档办公

Nano Pdf

使用纳米-pdf CLI编辑带有自然语言指令的PDF.

文档办公

Word / DOCX

创建,检查,并编辑有可靠样式的Microsoft Word文档和DOCX文件,编号,跟踪更改,表格,章节,并进行相容性检查. 当 (1) 任务涉及 Word 或 ".docx " 时使用; (2) 文件包括跟踪的更改,评论,字段,表格,模板,或页面布局限制; (3) 文档必须在不…

文档办公

Baidu Search

使用Baidu AI搜索引擎(BDSE)搜索网页. 用于实时信息、文件或研究专题.