Home
cd ../playbooks
File OrganizationAdvanced

Word Document Manipulation

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

10 minutes
By communitySource
#docx#word#manipulation#editing

You need to generate 200 personalized offer letters, update headers across 50 reports, or merge data into Word templates — and doing it by hand means clicking through each file one by one until your eyes glaze over.

Who it's for: operations teams generating bulk documents, HR departments creating personalized letters, consultants producing templated reports, legal teams updating contract boilerplate, anyone who edits the same Word doc structure repeatedly

Example

"Generate 150 personalized offer letters from this CSV and Word template" → Python script that merges employee data into your template, applies correct formatting, adds signatures, and outputs 150 individual .docx files — in seconds, not hours

CLAUDE.md Template

New here? 3-minute setup guide → | Already set up? Copy the template below.

Or install from your terminal:
npx ccplaybooks add docx-manipulation
# DOCX Manipulation

## Overview

This workflow 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

Get new playbooks like this one

One email a week with new Claude Code workflows. Free, like everything here.

No spam. Unsubscribe anytime.

README.md

What This Does

This workflow 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.


Quick Start

Step 1: Create a Project Folder

mkdir -p ~/Documents/DocxManipulation

Step 2: Download the Template

Click Download above, then:

mv ~/Downloads/CLAUDE.md ~/Documents/DocxManipulation/

Step 3: Start Working

cd ~/Documents/DocxManipulation
claude

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"

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

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

$Related Playbooks

File Organization

7-Minute Digital Declutter

Complete digital cleanup of photos, documents, and downloads in 7 minutes with intelligent recommendations.

5 minutes
Beginner
File Organization

CSV Data Visualizer

Create professional data visualizations, statistical reports, and interactive dashboards from CSV files for analysis and presentations.

5 minutes
Beginner
File Organization

Data Analyst Toolkit — CSV Analysis & Dashboard Generator

Analyze CSV and Excel data with automatic missing value detection, intelligent imputation, and interactive Plotly dashboards. Generate exploratory data analysis reports in minutes with Claude Code.

10 minutes
Intermediate
File Organization

Disk Space Analyzer

Find exactly what's eating your disk space with categorized breakdown and prioritized cleanup recommendations.

5 minutes
Beginner
File Organization

Duplicate File Detector

Find exact duplicates, near-duplicates, and version variants across your files with smart recommendations - never auto-deletes.

5 minutes
Beginner
File Organization

CSV & Excel Data Analyst

Ask questions about your spreadsheets in plain English. Get insights, summaries, and visualizations without knowing formulas or pivot tables.

5 minutes
Beginner
File Organization

Smart File Organizer

Organize and rename files based on content analysis

10 minutes
Advanced
File Organization

Natural Language Home Automation

Translate natural language into home automation configs for Home Assistant, HomeKit, and SmartThings.

10 minutes
Intermediate
File Organization

Intelligent File Organizer

Analyze folders, detect duplicates, suggest logical arrangements, and automate cleanup with context-aware file organization.

5 minutes
Beginner
File Organization

Document Layout Analyzer

Detect text blocks, tables, figures, and reading order in complex documents using surya.

10 minutes
Beginner
File Organization

Mac Performance Diagnostics

Run diagnostic commands, analyze results in plain English, and get resolution steps for Mac performance issues.

5 minutes
Beginner
File Organization

Markdown to Office Converter

Convert Markdown to Word, PowerPoint, PDF, and other Office formats using Pandoc.

10 minutes
Advanced

Browse all File Organization playbooks →