Python 办公自动化:Word 与 PowerPoint 处理

在日常的 HR、行政甚至运营等场景里,总少不了重复劳动密集型的文档/PPT产出

  • HR同学可能要给100个新员工发入职Offer
  • 行政要制作带公司logo、编号、姓名的季度表彰卡
  • 运营要生成N份格式统一但核心数据不同的周报附件

这些活儿不难,但机械校对、替换、排版费时费力还容易出错。其实完全可以用 Python 的“模板+数据映射模式一键搞定,今天就聊聊怎么用两个库快速上手。


核心工具库

在 Python 生态,这两个领域几乎是「标准解决方案」:

  • Word 处理python-docx(微软 .docx 专属,旧版 .doc 需要转成新格式)
  • PPT 处理python-pptx(仅支持 .pptx,同理旧版先转换)

先安装起来:

# 建议用国内镜像源更快,比如清华源
pip install python-docx python-pptx -i https://pypi.tuna.tsinghua.edu.cn/simple

一、Word 自动化:从基础到批量生产

1.1 简单上手:从零写一页演示文档

python-docx 的设计逻辑非常直观,把 .docx 拆解成 Document → Paragraph → Run 三层结构,每一层各司其职:

层级作用
Document整个文档的容器(保存/保存/还是保存)
Paragraph普通段落、标题的容器
Run同一段落内的「独立格式块」(加粗/字号是不同 Run)

先写一段生成基础演示页的代码:

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

# 1. 初始化空文档
doc = Document()

# 2. 添加标题、段落(注意层级 0 是大标题,层级1-9是小标题)
doc.add_heading('Python 办公自动化入门实战', 0)
# 写一段有两种样式的文字
p = doc.add_paragraph('Python 不止能写爬虫、做AI,还是')
# 添加第一个「加粗+14号」的独立块
highlight_run = p.add_run('职场摸鱼效率翻倍')
highlight_run.bold = True
highlight_run.font.size = Pt(14)
highlight_run.font.color.rgb = None  # 默认黑色,如果改色可设置 RGB 值
p.add_run('的神器!')

# 3. 插入图片(指定宽度,高度按比例自动缩放)
try:
    doc.add_picture('company_logo.png', width=Cm(5))
except FileNotFoundError:
    print("⚠️  找不到 company_logo.png,跳过图片插入")

# 4. 插入带边框的表格
table = doc.add_table(rows=1, cols=3)
# 设置样式为自带的「带网格线的表格」
table.style = 'Table Grid'
# 填充表头
header_cells = table.rows[0].cells
header_cells[0].text = '编号'
header_cells[1].text = '员工姓名'
header_cells[2].text = '入职部门'

# 5. 保存文件
doc.save('python_docx_demo.docx')
print("✅  基础 Word 文档生成成功!")

1.2 进阶核心:模板批量生成(重点!)

从零写文档只能做通用的演示,**真正能解放双手的是「基于Word模板的替换」。

制作模板的小技巧

先在 Word 里手动做好样式完美的模板,比如入职Offer、离职证明,然后用 双大括号 标记占位符:{employee_name}{entry_date}{position}

⚠️ 踩坑提醒: 不要在 Word 里一次性选中占位符的一部分改颜色加粗!!! 不然生成的 Run 会被拆碎,替换时可能会有部分占位符替换不上。**正确做法是:写占位符时先写纯文本,等替换逻辑调通后,再在模板里给整个占位符统一改样式。

完整的批量替换脚本

from docx import Document
from docx.oxml.ns import qn  # 这行如果不需要修改表格/占位符拆碎的备用方案

def fill_word_template(template_path, data_list, output_prefix):
    """
    批量填充Word模板并保存
    :param template_path: 模板文件路径
    :param data_list: 待填充的数据列表(每个元素是字典)
    :param output_prefix: 输出文件的前缀
    """
    for index, item in enumerate(data_list):
        doc = Document(template_path)
        # 替换段落中的占位符
        for p in doc.paragraphs:
            for run in p.runs:
                # 遍历所有键值对替换
                for key, value in item.items():
                    placeholder = f'{{{key}}}'
                    if placeholder in run.text:
                        run.text = run.text.replace(placeholder, str(value))
        
        # 替换表格中的占位符
        for table in doc.tables:
            for row in table.rows:
                for cell in row.cells:
                    for p in cell.paragraphs:
                        for run in p.runs:
                            for key, value in item.items():
                                placeholder = f'{{{key}}}'
                                if placeholder in run.text:
                                    run.text = run.text.replace(placeholder, str(value))
        
        # 生成文件名(用姓名+序号或者纯序号都可以)
        output_file = f'{output_prefix}_{item["employee_name"]}_{index+1}.docx'
        doc.save(output_file)
        print(f"✅  已生成 {output_file}")

# ------------------ 测试数据 ------------------
employee_data = [
    {
        "employee_name": "骆昊",
        "entry_date": "2026-04-01",
        "position": "高级架构师",
        "department": "技术中台",
        "salary": "35K"
    },
    {
        "employee_name": "王大锤",
        "entry_date": "2026-04-02",
        "position": "全栈开发工程师",
        "department": "电商业务线",
        "salary": "18K"
    }
]

# ------------------ 调用函数 ------------------
if __name__ == "__main__":
    fill_word_template(
        template_path="entry_offer_template.docx",
        data_list=employee_data,
        output_prefix="2026Q2_入职Offer"
    )

二、PPT 自动化:用模板生成+内容页

PPT 的核心逻辑是**母版布局→占位符→填充,先制作或使用预设的布局,比从零写布局更稳定。

2.1 基础:用预设布局写演示PPT

先看一段用 python-pptx 自带布局生成两页PPT的代码:

from pptx import Presentation
from pptx.util import Inches  # 英寸是PPT常用单位,还有 Cm
from pptx.dml.color import RGBColor

# 1. 初始化演示文稿(默认是宽屏16:9的空白母版)
prs = Presentation()

# 2. 添加第一页(标题页,对应布局索引0)
title_layout = prs.slide_layouts[0]
slide1 = prs.slides.add_slide(title_layout)
# 填充标题和副标题
title_shape = slide1.shapes.title
subtitle_shape = slide1.placeholders[1]
title_shape.text = "2026Q1 部门效率提升报告"
subtitle_shape.text = "汇报人:技术中台\n汇报时间:2026-03-25"

# 3. 添加第二页(标题+内容,对应布局索引1)
content_layout = prs.slide_layouts[1]
slide2 = prs.slides.add_slide(content_layout)
# 填充标题
slide2.shapes.title.text = "核心工作成果"
# 填充内容列表
content_frame = slide2.placeholders[1].text_frame
content_frame.text = "1. 入职Offer/离职证明自动化上线"
# 添加第二级列表
p2 = content_frame.add_paragraph()
p2.text = "   - 效率提升约 300%"
p2.level = 1
# 添加第三行列表
p3 = content_frame.add_paragraph()
p3.text = "   - 人工错误率降为0%"
p3.level = 1
# 添加第三页(标题+图片)
pic_layout = prs.slide_layouts[5]  # 索引5是空白页,自己加图片和标题更自由
slide3 = prs.slides.add_slide(pic_layout)
# 添加标题(用 add_titlebox
title_box = slide3.shapes.add_title
title_box.text = "自动化工具使用流程图"
# 添加图片
try:
    left = Inches(1)
    top = Inches(2)
    height = Inches(4)
    slide3.shapes.add_picture('automation_flowchart.png', left, top, height=height)
except FileNotFoundError:
    print("⚠️  找不到流程图,跳过插入")

# 4. 保存文件
prs.save('2026Q1_效率提升报告.pptx')
print("✅  基础PPT生成成功!")

三、总结与展望

核心要点

  1. Word
    • 牢记三层结构:Document→Paragraph→Run
    • 重点用模板批量生成才是真·摸鱼神器
    • 占位符要统一写纯文本,调通再改样式
  2. PPT
    • 用预设布局(索引0-9对应不同空白/带占位符的母版
    • 优先用占位符填充,实在不行用 add_* 系列函数自己加

适用场景

这类脚本属于「一劳永逸小工程」,虽然前期可能需要调1-2小时,但以后每做一次就能顶10-100份文档/PPT,还不用担心格式、错别字问题。

如果需要更复杂的功能(比如Word插入Excel图表、PPT插入带数据的柱状图折线图、邮件自动发),可以继续研究这两个库的官方文档哦~