Use python-docx to create and edit Word documents (.docx).
Use Cases
- The user says "help me generate a Word report" or "write this content into Word"
- The user needs to create formatted documents (headings, tables, lists)
- The user needs to modify an existing Word file
Dependency Installation
pip install python-docx
Create Document
from docx import Document
from docx.shared import Inches, Pt, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = Document()
# 标题
doc.add_heading('报告标题', level=0)
# 段落
p = doc.add_paragraph('这是正文内容。')
p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
# 加粗和斜体
p = doc.add_paragraph()
p.add_run('加粗文本').bold = True
p.add_run(',')
p.add_run('斜体文本').italic = True
# 列表
doc.add_paragraph('要点一', style='List Bullet')
doc.add_paragraph('要点二', style='List Bullet')
# 编号列表
doc.add_paragraph('第一步', style='List Number')
doc.add_paragraph('第二步', style='List Number')
# 表格
table = doc.add_table(rows=3, cols=3, style='Table Grid')
table.cell(0, 0).text = '姓名'
table.cell(0, 1).text = '部门'
table.cell(0, 2).text = '职位'
# 分页
doc.add_page_break()
# 保存
output_path = '/tmp/report.docx'
doc.save(output_path)
print(f'文档已保存: {output_path}')
Read Document
from docx import Document
doc = Document('/path/to/input.docx')
# 读取所有段落
for para in doc.paragraphs:
print(f'[{para.style.name}] {para.text}')
# 读取表格
for table in doc.tables:
for row in table.rows:
print([cell.text for cell in row.cells])
Modify Document
from docx import Document
doc = Document('/path/to/input.docx')
# 修改段落文本
for para in doc.paragraphs:
if '旧内容' in para.text:
for run in para.runs:
run.text = run.text.replace('旧内容', '新内容')
doc.save('/path/to/output.docx')
Output Specifications
- By default, save to
/tmp/or a user-specified path - After generation, inform the user of the file path
- If on macOS, use the
opencommand to open a file preview