← Back to Skills
Productivity

Document Processing (DOCX)

Create and manipulate Microsoft Word documents programmatically. Use when users need to generate, edit, or convert Word documents.

Create and manipulate Microsoft Word documents programmatically using Python.

Setup

Installation

pip install python-docx

Basic Usage

from docx import Document

# Create document
doc = Document()

# Add content
doc.add_heading('Document Title', 0)
doc.add_paragraph('Hello, World!')

# Save
doc.save('document.docx')

Document Structure

Sections and Headings

# Main heading
doc.add_heading('Main Title', 0)

# Section headings
doc.add_heading('Section 1', level=1)
doc.add_heading('Subsection 1.1', level=2)

# Paragraphs
doc.add_paragraph('This is a paragraph.')

Lists

# Bullet list
doc.add_paragraph('Item 1', style='List Bullet')
doc.add_paragraph('Item 2', style='List Bullet')

# Numbered list
doc.add_paragraph('First item', style='List Number')
doc.add_paragraph('Second item', style='List Number')

Tables

# Create table
table = doc.add_table(rows=3, cols=3)

# Add data
for i, row in enumerate(table.rows):
    for j, cell in enumerate(row.cells):
        cell.text = f'Row {i}, Col {j}'

# Style table
table.style = 'Table Grid'

Advanced Features

Formatting

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

# Paragraph formatting
paragraph = doc.add_paragraph()
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

# Run formatting
run = paragraph.add_run('Bold text')
run.bold = True

run = paragraph.add_run('Italic text')
run.italic = True

run = paragraph.add_run('Large text')
run.font.size = Pt(14)

Images

doc.add_picture('image.png', width=Inches(4))

# Add with alignment
from docx.enum.text import WD_ALIGN_PARAGRAPH
paragraph = doc.add_paragraph()
run = paragraph.add_run()
run.add_picture('image.png', width=Inches(4))
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

Headers and Footers

section = doc.sections[0]
header = section.header
header_para = header.paragraphs[0]
header_para.text = 'Document Header'

footer = section.footer
footer_para = footer.paragraphs[0]
footer_para.text = 'Page number: '

Template System

Using Templates

from docx import Document

# Load template
doc = Document('template.docx')

# Replace placeholders
for paragraph in doc.paragraphs:
    if '{{NAME}}' in paragraph.text:
        paragraph.text = paragraph.text.replace('{{NAME}}', 'John Doe')
    if '{{DATE}}' in paragraph.text:
        paragraph.text = paragraph.text.replace('{{DATE}}', '2024-01-15')

# Save with new name
doc.save('output.docx')

Dynamic Content

def create_report(data):
    doc = Document()
    doc.add_heading(f'Report: {data["title"]}', 0)
    
    # Add summary
    doc.add_heading('Summary', level=1)
    doc.add_paragraph(data['summary'])
    
    # Add data table
    doc.add_heading('Data', level=1)
    table = doc.add_table(rows=len(data['items']) + 1, cols=2)
    table.style = 'Table Grid'
    
    # Header row
    table.rows[0].cells[0].text = 'Item'
    table.rows[0].cells[1].text = 'Value'
    
    # Data rows
    for i, item in enumerate(data['items']):
        table.rows[i + 1].cells[0].text = item['name']
        table.rows[i + 1].cells[1].text = str(item['value'])
    
    return doc

Best Practices

  • Use templates for consistent formatting
  • Handle errors gracefully
  • Validate input data
  • Close documents properly
  • Use context managers when possible
  • Test with different Word versions
  • Consider PDF conversion for distribution