Skip to main content
skill CX Codex

docx-manipulation — Claude Code skill for Word docs

The skill builds and edits Word files through python-docx: headings, tables, images, headers. Useful when a report or contract has to come out of code.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add claude-office-skills/skills --skill docx-manipulation -a claude-code
Open on GitHub

What docx-manipulation does

The skill hands the agent working knowledge of python-docx. You describe what the document should contain, pass in source text or data, and the agent writes and runs the code. Inside are sections on document structure, paragraphs and headings, tables with merged cells, images, character formatting, page setup, headers and footers, and styles.

There are ready patterns: a report with per-section headings, a table built from a list of rows, and placeholder filling where {key} markers get replaced. The listed practices are planning the hierarchy before coding, sticking to styles instead of manual formatting, calling doc.save() periodically on large files, and checking that a file exists before opening it.

The skill declares an integration with the office-mcp MCP server and its tools: create_docx, extract_text_from_docx, fill_docx_template, merge_docx_files. If you plan to lean on python-docx alone, those four operations are yours to write — worth checking whether office-mcp is running on your side. Recommended models are claude-sonnet-4 and claude-opus-4, with claude-3-5-sonnet, gpt-4 and gpt-4o listed as compatible.

What it helps with

  • build a report with headings and a data table
  • fill a contract template from placeholder keys
  • add a header and page numbering
  • place a logo inside a specific paragraph
  • merge several docx files into one

Example prompts for the agent

  • Create a report with a title, sections and an expense table
  • Fill the contract template: {client}, {amount}, {date}
  • Add a header with the company name and page numbers

How to install docx-manipulation

1Skills CLI (Vercel)

npx skills add claude-office-skills/skills --skill docx-manipulation -a claude-code

2Manually: put the files in place

~/.claude/skills/docx-manipulation/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/docx-manipulation/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about docx-manipulation

How do I install docx-manipulation in Claude Code?

Run npx skills add claude-office-skills/skills --skill docx-manipulation -a claude-code. The skill file lands at ~/.claude/skills/docx-manipulation/SKILL.md.

What does docx-manipulation do?

It teaches the agent to create and edit Word documents with python-docx: paragraphs, headings, tables, images, styles, headers and footers, and page setup.

What does the skill need to work?

The python-docx library, and for operations like create_docx or merge_docx_files the office-mcp MCP server with its tools.

Source text

SKILL.md · MIT
---
# ═══════════════════════════════════════════════════════════════════════════════
# 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

```python
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
```python
# 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
```python
# 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
```python
# 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
```python
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
```python
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
```python
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
```python
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
```python
# 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
```python
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
```python
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
```python
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
```python
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
```python
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

```bash
pip install python-docx
```

## Resources

- [python-docx Documentation](https://python-docx.readthedocs.io/)
- [GitHub Repository](https://github.com/python-openxml/python-docx)
- [Office Open XML Spec](https://docs.microsoft.com/en-us/office/open-xml/open-xml-sdk)

© claude-office-skills · MIT · claude-office-skills/skills

Similar skills

Everything for Office documents →

From the same set109

google-ads-manager Helps plan Google Ads campaigns, group search keywords, write RSA ad copy, and prepare reporting. Useful when organizing paid search workflows. CX Codex +1 6,300installs airtable-automation Gives an agent patterns for Airtable base design, views, formulas and automation flows. Use it when tasks, projects or n8n workflows need a clear data structure. CX Codex +1 6,200installs telegram-bot A skill for building Telegram bots: chatbots, notifications, AI assistants and group automation. Useful when you need message handlers and workflows fast. CX Codex +1 6,200installs academic-search Builds academic search strategies, reviews supplied papers and abstracts, and helps synthesize findings. Use it when planning a literature review or assessing research methods. CX Codex +1 6,100installs calendar-automation Automates Google Calendar and Outlook workflows: allocates focus time blocks, sends morning Slack briefings, and prepares meeting notes with context. CX Codex +1 6,100installs pdf-to-docx Turns PDF files into editable Word documents with the pdf2docx library. Useful when a report or contract needs changes, not just reading. CX Codex +1 6,000installs proposal-writer Generates structured business proposals, quick service quotes, and partnership pitches. Useful for client negotiations and RFP responses. CX Codex +1 5,900installs PDF OCR Extraction Pulls text out of scanned and image-based PDFs with OCR. Useful when a document won't let you select anything but still needs to be searchable. CX Codex +1 5,700installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor