by @anthropic
A comprehensive Word document skill using python-docx. Create professional documents with headings, tables, images, bullet lists, numbered lists, headers/footers, custom styles, and precise formatting. Read and edit existing .docx files with content modification and structural changes.
Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files). This includes any mention of 'Word doc', '.docx', or requests for professional documents with formatting like tables of contents, headings, page numbers, or letterheads.
A .docx file is a ZIP archive containing XML files. In this sandbox, use python-docx for all document operations.
| Task | Approach |
|---|---|
| Read/analyze content | python-docx to extract text and structure |
| Create new document | python-docx — see Creating New Documents |
| Edit existing document | python-docx — load and modify |
from docx import Document
from docx.shared import Inches, Pt, Cm, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
doc = Document()
# Page setup
section = doc.sections[0]
section.page_width = Inches(8.5)
section.page_height = Inches(11)
section.top_margin = Inches(1)
section.bottom_margin = Inches(1)
section.left_margin = Inches(1)
section.right_margin = Inches(1)
# Title
title = doc.add_heading('Document Title', level=0)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
# Paragraph with formatting
paragraph = doc.add_paragraph()
run = paragraph.add_run('Bold text ')
run.bold = True
run.font.size = Pt(12)
run.font.color.rgb = RGBColor(0, 0, 0)
run2 = paragraph.add_run('and normal text.')
run2.font.size = Pt(12)
# Heading
doc.add_heading('Section 1', level=1)
doc.add_paragraph('Section content here.')
# Bullet list
doc.add_paragraph('First item', style='List Bullet')
doc.add_paragraph('Second item', style='List Bullet')
# Numbered list
doc.add_paragraph('Step one', style='List Number')
doc.add_paragraph('Step two', style='List Number')
doc.save('output.docx')
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.oxml.ns import qn
from do...