---
name: anthropic-docx
description: Read, create, and edit .docx files using python-docx. Supports creating documents with text, tables, images, and rich formatting; extracting content from existing documents; and making targeted edits while preserving document structure.
license: Complete terms in LICENSE.txt
---

# DOCX Skill

A skill for reading, creating, and editing .docx (Word) documents using python-docx.

## Installation

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

## Reading Documents

Use `python-docx` to extract content:

```python
from docx import Document

doc = Document("path/to/document.docx")

# Extract paragraphs
for para in doc.paragraphs:
    print(f"[{para.style.name}] {para.text}")

# Extract tables
for table in doc.tables:
    for row in table.rows:
        for cell in row.cells:
            print(cell.text)

# Extract headers and footers
for section in doc.sections:
    header = section.header
    footer = section.footer
    for para in header.paragraphs:
        print(f"Header: {para.text}")
    for para in footer.paragraphs:
        print(f"Footer: {para.text}")
```

## Creating Documents

```python
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT

doc = Document()

# Title
title = doc.add_heading("Document Title", level=0)

# Paragraph with formatting
p = doc.add_paragraph()
run = p.add_run("Bold and colored text")
run.bold = True
run.font.color.rgb = RGBColor(0xFF, 0x00, 0x00)
run.font.size = Pt(14)

# Add a table
table = doc.add_table(rows=3, cols=3)
table.style = "Light Grid Accent 1"
for i, row in enumerate(table.rows):
    for j, cell in enumerate(row.cells):
        cell.text = f"Row {i}, Col {j}"

# Add an image
doc.add_picture("path/to/image.png", width=Inches(6))

# Page break
doc.add_page_break()

doc.save("output.docx")
```

## Editing Existing Documents

```python
from docx import Document

doc = Document("existing.docx")

# Find and replace text in paragraphs
for para in doc.paragraphs:
    if "old text" in para.text:
        for run in para.runs:
            if "old text" in run.text:
                run.text = run.text.replace("old text", "new text")

# Add content to an existing document
doc.add_paragraph("New paragraph at the end")

doc.save("modified.docx")
```

## Best Practices

- Always work with a copy of important documents
- Check that python-docx is installed before using
- Handle file encoding issues gracefully
- Use context managers (`with`) when possible
- For complex templates, consider using placeholder text and replacing it
