Python操作Word和Powerpoint文件
基础教学 1 min read

Python操作Word和Powerpoint文件

Blog Author

Python操作Word和PowerPoint文件:教学式指南


一、前言:为什么用Python来处理Office文档?

在企业办公、学校作业、报告生成等场景中,我们经常遇到需要反复填写模板文档(如离职证明、成绩单、合同、PPT报告)的问题。使用Python自动化处理这些任务,可以显著节省时间、减少错误,提升效率。

Python 提供了优秀的第三方库:

  • python-docx:用于创建、修改 .docx 格式的 Word 文档;
  • python-pptx:用于生成和操作 PowerPoint 演示文稿(.pptx 格式)。

二、Word 文档操作:从创建到批量生成

安装工具包

pip install python-docx

创建Word文档:基本内容添加

以下代码展示了如何创建一个 Word 文件并添加标题、段落、列表、图片、表格等元素:

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


document = Document()
document.add_heading('快快乐乐学Python', 0)


p = document.add_paragraph('Python是一门非常流行的编程语言,它')
run = p.add_run('简单')
run.bold = True
run.font.size = Pt(18)
p.add_run('而且')
run = p.add_run('优雅')
run.font.size = Pt(18)
run.underline = True
p.add_run('。')


# 添加标题和样式段落
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')


# 添加列表
document.add_paragraph('第一项', style='List Bullet')
document.add_paragraph('第一项(编号)', style='List Number')


# 插入图片(需要图片存在)
document.add_picture('resources/guido.jpg', width=Cm(5.2))


# 插入表格
table = document.add_table(rows=1, cols=3)
table.style = 'Dark List'
hdr_cells = table.rows[0].cells
hdr_cells[0].text = '姓名'
hdr_cells[1].text = '性别'
hdr_cells[2].text = '出生日期'
for name, sex, birthday in [('骆昊', '男', '1995-5-5')]:
    row_cells = table.add_row().cells
    row_cells[0].text = name
    row_cells[1].text = sex
    row_cells[2].text = birthday


# 保存文档
document.save('demo.docx')

读取现有Word文档内容

场景:当你需要审阅、提取或替换文档内容时。

from docx import Document
doc = Document('resources/离职证明.docx')
for no, p in enumerate(doc.paragraphs):
    print(no, p.text)

Word模板替换:批量生成离职证明

应用场景

  • 批量生成 离职证明
  • 自动填充 合同、实习证明、推荐信

操作步骤

  1. 创建一个Word模板文件,用占位符 {name}{id} 代替真实信息;
  2. 用Python读取模板,循环替换并保存新文件。
from docx import Document


employees = [
    {
        'name': '骆昊',
        'id': '100200198011280001',
        'sdate': '2008年3月1日',
        'edate': '2012年2月29日',
        'department': '产品研发',
        'position': '架构师',
        'company': '成都华为技术有限公司'
    },
    ...
]


for emp_dict in employees:
    doc = Document('resources/离职证明模板.docx')
    for p in doc.paragraphs:
        for run in p.runs:
            if '{' in run.text:
                start = run.text.find('{')
                end = run.text.find('}')
                key = run.text[start+1:end]
                run.text = run.text.replace(f'{{{key}}}', emp_dict[key])
    doc.save(f'{emp_dict["name"]}离职证明.docx')

三、PowerPoint 幻灯片操作:自动生成展示文稿

安装库

pip install python-pptx

创建基础演示文稿

以下是创建两页幻灯片的示例:

from pptx import Presentation


pres = Presentation()


# 添加标题页
slide1 = pres.slides.add_slide(pres.slide_layouts[0])
slide1.shapes.title.text = "Welcome to Python"
slide1.placeholders[1].text = "Life is short, I use Python"


# 添加内容页
slide2 = pres.slides.add_slide(pres.slide_layouts[1])
slide2.shapes.title.text = "Introduction"
body = slide2.placeholders[1].text_frame
body.text = "History of Python"


p = body.add_paragraph()
p.text = "X'mas 1989"
p.level = 1


p = body.add_paragraph()
p.text = "Guido began to write interpreter for Python."
p.level = 2


pres.save('test.pptx')

四、最佳实践与技巧总结

使用场景 推荐操作方式
批量生成合同/证明 使用 Word 模板 + python-docx 进行替换
课程/项目报告PPT自动化 使用 python-pptx 动态生成
多人证书制作 模板替换 + 字体样式统一设置
读取已有文档内容分析 遍历 paragraphs 提取文字内容
避免样式丢失 避免直接修改段落文本,使用 run 元素修改

五、教学建议:面向初学者的练习任务

Word篇:

  1. 基础任务:创建一个包含标题、图片、表格、列表的Word文档。
  2. 进阶任务:制作一个带占位符的Word模板,批量生成学生成绩单。
  3. 挑战任务:读取现有的报告文档,对某一关键词自动加粗或添加注释。

PowerPoint篇:

  1. 基础任务:创建一页标题+内容的幻灯片。
  2. 进阶任务:生成一个包含5页内容结构的课程讲义PPT。
  3. 挑战任务:自动从CSV读取课程大纲,批量生成每页幻灯片。

六、总结

Python 的办公自动化能力可以显著提高日常工作的效率,特别适合HR、行政、老师、工程师、数据分析师等角色。通过学习 python-docxpython-pptx,你可以轻松实现从“手工制作”到“批量自动化”的跨越。

记住:写程序是苦的,但程序自动化工作是甜的。


是否需要我继续扩展:如读取Excel作为批量数据源、自动发送Word/PPT作为邮件附件等?