python-docx 模块常用函数与示例

1. 安装与基本使用

# 通过 pip 安装
pip install python-docx

# 导入核心类
from docx import Document
    

2. 创建与保存文档

Document()

# 新建空白文档
doc = Document()
# 保存到本地
doc.save('example.docx')
    

3. 添加段落与标题

add_paragraph(text, style=None)

doc.add_paragraph('这是一个普通段落。')
doc.add_paragraph('使用自定义样式的段落。', style='Intense Quote')
    

add_heading(text, level=1)

doc.add_heading('一级标题', level=1)
doc.add_heading('二级标题', level=2)
doc.add_heading('三级标题', level=3)
    

4. 插入图片

add_picture(image_path, width=None, height=None)

# 插入图片,宽度设为 5 cm(高度自动等比)
doc.add_picture('logo.png', width=docx.shared.Cm(5))
    

5. 表格操作

add_table(rows, cols, style=None)

table = doc.add_table(rows=3, cols=4, style='Light Grid')
# 填充单元格
for i in range(3):
    for j in range(4):
        table.cell(i, j).text = f'R{i+1}C{j+1}'
    

访问已有表格

# 假设文档里已经有表格
for table in doc.tables:
    for row in table.rows:
        for cell in row.cells:
            print(cell.text)
    

6. 样式与段落格式

paragraph.style

para = doc.add_paragraph('使用标题样式')
para.style = 'Heading 2'
    

run(文字块)属性

para = doc.add_paragraph()
run = para.add_run('加粗斜体')
run.bold = True
run.italic = True
run.underline = True
run.font.size = docx.shared.Pt(14)
    

7. 页面布局

sections

section = doc.sections[0]
# 设置页边距(单位为英寸)
section.top_margin = docx.shared.Inches(1)
section.bottom_margin = docx.shared.Inches(1)
section.left_margin = docx.shared.Inches(1)
section.right_margin = docx.shared.Inches(1)
    

添加分页符

doc.add_page_break()
    

8. 读取已有文档

doc = Document('existing.docx')
# 遍历所有段落
for para in doc.paragraphs:
    print(para.text)
    

9. 完整示例(创建一份包含标题、段落、图片、表格的文档)

from docx import Document
from docx.shared import Cm, Pt, Inches

doc = Document()

# 标题
doc.add_heading('Python‑docx 示例文档', level=1)

# 段落
p = doc.add_paragraph('下面展示了 python-docx 的常用功能。')
p.add_run('(加粗)').bold = True

# 插入图片
doc.add_picture('sample.jpg', width=Cm(8))

# 表格
table = doc.add_table(rows=2, cols=3, style='Medium Grid 1 Accent 1')
table.cell(0,0).text = '姓名'
table.cell(0,1).text = '年龄'
table.cell(0,2).text = '城市'
table.cell(1,0).text = '张三'
table.cell(1,1).text = '28'
table.cell(1,2).text = '北京'

# 页面设置
section = doc.sections[0]
section.top_margin = Inches(1)
section.bottom_margin = Inches(1)

# 保存
doc.save('demo.docx')
    

demo.docx 将展示标题、段落、图片、表格以及页面布局的效果。