python-pptx 使用教程:Python 操作 PPT 全指南

前言

在日常开发中,经常需要自动化生成报表、周报或数据汇报 PPT。
手动制作不仅耗时,还容易出错。
python-pptx 是一个纯 Python 库,无需安装 Microsoft Office,即可程序化创建和修改 .pptx 文件。
本文将从安装到实战,覆盖 python-pptx 的核心功能,帮助你快速上手自动化 PPT 生成。

依赖

安装 python-pptx:

1
pip install python-pptx

如需生成图表,还需安装 lxml(通常已随 python-pptx 一起安装):

1
pip install lxml

核心对象

python-pptx 的 API 围绕以下几个核心对象展开。
理解它们的层级关系是高效使用该库的关键。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Presentation                    # 演示文稿(顶层对象)
├── slides # 幻灯片集合
│ └── Slide # 单张幻灯片
│ ├── shapes # 形状集合
│ │ └── Shape # 形状(文本框/图片/表格/图表等)
│ │ └── text_frame
│ │ ├── Paragraph # 段落
│ │ │ └── Run # 文本片段(同一格式)
│ │ └── ...
│ └── placeholders # 布局占位符集合
├── slide_layouts # 幻灯片布局集合
│ └── SlideLayout # 单个布局
├── slide_masters # 母版集合
│ └── SlideMaster # 单个母版
└── core_properties # 文档属性(标题/作者等)

Presentation

演示文稿的顶层入口,管理所有幻灯片、布局和母版。

1
2
3
4
5
6
7
8
9
from pptx import Presentation

prs = Presentation() # 新建空白 PPT
prs = Presentation("a.pptx") # 打开已有 PPT

prs.slides # -> Slide 对象的集合
prs.slide_layouts # -> SlideLayout 对象的集合(内置 9 种)
prs.slide_masters # -> SlideMaster 对象的集合
prs.core_properties # -> 文档元数据(title, author, subject...)

Slide

单张幻灯片,是所有内容的容器。

1
2
3
4
5
6
slide = prs.slides.add_slide(prs.slide_layouts[1])

slide.shapes # -> Shape 集合,用于遍历或添加元素
slide.placeholders # -> 占位符集合(来自布局定义)
slide.slide_layout # -> 关联的 SlideLayout
slide.slide_id # -> 幻灯片唯一 ID

SlideLayout 与 SlideMaster

  • SlideMaster:母版,控制全局背景、字体、配色
  • SlideLayout:布局,定义幻灯片中占位符的位置和类型
1
2
3
4
5
master = prs.slide_masters[0]
layout = prs.slide_layouts[1]

layout.name # -> "Title and Content"
layout.placeholders # -> 该布局包含的占位符

Shape

幻灯片上所有可视元素的基类,常见子类:

类型 说明 创建方法
TextFrame 文本框 shapes.add_textbox()
Picture 图片 shapes.add_picture()
Table 表格 shapes.add_table()
GraphicFrame 图表 shapes.add_chart()
AutoShape 自动形状(矩形/圆形等) shapes.add_shape()

通用属性:

1
2
3
4
5
6
7
shape.left            # -> 距左边界距离(Emu)
shape.top # -> 距上边界距离(Emu)
shape.width # -> 宽度(Emu)
shape.height # -> 高度(Emu)
shape.has_text_frame # -> True/False
shape.text # -> 快捷获取/设置文本
shape.shape_type # -> 形状类型枚举

TextFrame / Paragraph / Run

文本内容的三层结构:

1
2
3
TextFrame(文本框)
└── Paragraph(段落)
└── Run(文本片段,同一格式)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
tf = shape.text_frame          # TextFrame
tf.text = "Hello" # 设置全文(清空原有内容)
tf.paragraphs[0] # 获取第一个段落
tf.add_paragraph() # 新增段落

p = tf.paragraphs[0] # Paragraph
p.text # 段落文本
p.alignment # 对齐方式
p.level # 缩进级别
p.space_before # 段前间距
p.space_after # 段后间距

run = p.add_run() # 新增 Run
run.text = "加粗文本"
run.font.bold = True # 格式仅作用于该 Run
run.font.size # 字号
run.font.color.rgb # 颜色

Placeholder

布局中预定义的占位符,通过索引或类型访问:

1
2
3
4
5
6
7
slide = prs.slides.add_slide(prs.slide_layouts[1])

title = slide.placeholders[0] # 标题占位符
title.text = "我的标题"

body = slide.placeholders[1] # 内容占位符
body.text = "正文内容"

尺寸

单位

python-pptx 中所有位置和尺寸都以 Emu(English Metric Units)为内部单位,1 Emu = 1/914400 英寸。
直接使用 Emu 不直观,因此 pptx.util 提供了常用的转换函数:

1
from pptx.util import Inches, Cm, Mm, Pt, Emu
单位 说明 示例
Inches(n) 英寸 Inches(1) → 1 英寸宽
Cm(n) 厘米 Cm(2.54) → 等同 1 英寸
Mm(n) 毫米 Mm(10) → 1 厘米
Pt(n) 磅(字号/线宽) Pt(12) → 12pt 字号
Emu(n) Emu 原始值 Emu(914400) → 1 英寸

在不同场景下的使用方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from pptx.util import Inches, Cm, Pt, Emu

# 位置与尺寸:使用 Inches 或 Cm
slide.shapes.add_textbox(Inches(1), Inches(2), Inches(5), Inches(1.5))
slide.shapes.add_picture("img.png", Cm(2), Cm(3), Cm(10), Cm(5))

# 字号与线宽:使用 Pt
run.font.size = Pt(14)
shape.line.width = Pt(2)

# 转换
value = Inches(1)
print(value) # -> 914400(Emu 原始值)
print(Inches(1).cm) # -> 2.54
print(Cm(2.54).inches) # -> 1.0

幻灯片尺寸

默认尺寸为 16:9 宽屏,单位同为 Emu:

比例 宽度 高度
16:9(默认) Inches(13.333) Inches(7.5)
4:3 Inches(10) Inches(7.5)
A4 竖版 Inches(8.27) Inches(11.69)
1
2
3
4
5
6
7
8
9
10
11
12
from pptx import Presentation
from pptx.util import Inches

prs = Presentation()

# 查看默认尺寸
print(prs.slide_width) # 12192000(Emu)
print(prs.slide_width.inches) # 13.333...

# 修改尺寸
prs.slide_width = Inches(10)
prs.slide_height = Inches(7.5)

实现

创建 PPT

最简示例,创建一个空白演示文稿并保存:

1
2
3
4
from pptx import Presentation

prs = Presentation()
prs.save("demo.pptx")

添加幻灯片与布局

PPT 使用布局(Layout)来定义幻灯片的结构。
python-pptx 默认提供 11 种内置布局:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from pptx import Presentation

prs = Presentation()

# 布局索引:
# 0: Title Slide
# 1: Title and Content
# 2: Section Header
# 3: Two Content
# 4: Comparison
# 5: Title Only
# 6: Blank
# 7: Content with Caption
# 8: Picture with Caption

slide = prs.slides.add_slide(prs.slide_layouts[1]) # 标题 + 内容布局
prs.save("demo.pptx")

添加文本框

通过 shapes.add_textbox 在幻灯片上添加自定义文本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from pptx import Presentation
from pptx.util import Inches, Pt

prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[6]) # Blank 布局

# 添加文本框 (left, top, width, height)
textbox = slide.shapes.add_textbox(Inches(1), Inches(1), Inches(5), Inches(2))
tf = textbox.text_frame
tf.text = "第一行文本"

# 添加段落
p = tf.add_paragraph()
p.text = "第二行文本"
p.level = 1 # 缩进级别

prs.save("demo.pptx")

设置文本格式

对文本进行字体、大小、颜色、加粗等格式设置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor

prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[6])

textbox = slide.shapes.add_textbox(Inches(1), Inches(1), Inches(5), Inches(2))
tf = textbox.text_frame
p = tf.paragraphs[0]
p.text = "格式化文本"

run = p.runs[0]
run.font.size = Pt(24) # 字号
run.font.bold = True # 加粗
run.font.italic = True # 斜体
run.font.color.rgb = RGBColor(0xFF, 0x66, 0x00) # 橙色
run.font.name = "微软雅黑" # 字体

prs.save("demo.pptx")

添加图片

在幻灯片中插入图片:

1
2
3
4
5
6
7
8
9
10
from pptx import Presentation
from pptx.util import Inches

prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[6])

# 添加图片 (left, top, width, height)
slide.shapes.add_picture("logo.png", Inches(1), Inches(1), Inches(3), Inches(2))

prs.save("demo.pptx")

添加表格

创建带样式的表格:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor

prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[6])

# 添加表格 (rows, cols, left, top, width, height)
rows, cols = 4, 3
table_shape = slide.shapes.add_table(rows, cols, Inches(1), Inches(1), Inches(6), Inches(3))
table = table_shape.table

# 设置列宽
table.columns[0].width = Inches(2)
table.columns[1].width = Inches(2)
table.columns[2].width = Inches(2)

# 填充表头
headers = ["姓名", "部门", "绩效"]
for i, header in enumerate(headers):
cell = table.cell(0, i)
cell.text = header
# 表头样式
cell.fill.solid()
cell.fill.fore_color.rgb = RGBColor(0x00, 0x70, 0xC0)
for paragraph in cell.text_frame.paragraphs:
for run in paragraph.runs:
run.font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)
run.font.bold = True

# 填充数据
data = [
["张三", "技术部", "A"],
["李四", "产品部", "B+"],
["王五", "设计部", "A-"],
]
for r, row_data in enumerate(data, start=1):
for c, value in enumerate(row_data):
table.cell(r, c).text = value

prs.save("demo.pptx")

添加图表

插入柱状图、折线图、饼图等,通过 add_chart 方法添加:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from pptx import Presentation
from pptx.util import Inches
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE

prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[6])

# 准备图表数据
chart_data = CategoryChartData()
chart_data.categories = ["Q1", "Q2", "Q3", "Q4"]
chart_data.add_series("销售额", (150, 200, 180, 250))
chart_data.add_series("利润", (30, 50, 40, 70))

# 添加图表 (left, top, width, height)
chart_shape = slide.shapes.add_chart(
XL_CHART_TYPE.COLUMN_CLUSTERED, # 柱状图
Inches(1), Inches(1), Inches(8), Inches(5),
chart_data
)

# 获取图表对象进行进一步设置
chart = chart_shape.chart
chart.has_legend = True
chart.legend.include_in_layout = False

prs.save("demo.pptx")

常用图表类型(通过 XL_CHART_TYPE 枚举指定):

1
2
3
4
5
6
7
8
from pptx.enum.chart import XL_CHART_TYPE

XL_CHART_TYPE.COLUMN_CLUSTERED # 簇状柱形图
XL_CHART_TYPE.LINE # 折线图
XL_CHART_TYPE.PIE # 饼图
XL_CHART_TYPE.BAR_CLUSTERED # 簇状条形图
XL_CHART_TYPE.AREA # 面积图
XL_CHART_TYPE.SCATTER # 散点图

设置形状样式

为形状添加边框、填充色,通过 fillline 属性控制:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor

prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[6])

# 添加一个矩形
shape = slide.shapes.add_shape(
1, # MSO_SHAPE.RECTANGLE
Inches(1), Inches(1), Inches(4), Inches(2)
)

# 填充颜色
shape.fill.solid()
shape.fill.fore_color.rgb = RGBColor(0x00, 0x70, 0xC0)

# 边框
shape.line.color.rgb = RGBColor(0x00, 0x00, 0x00)
shape.line.width = Pt(2)

# 文字
shape.text = "带样式的矩形"

prs.save("demo.pptx")

操作已有 PPT

读取并修改现有的 PPT 文件,通过遍历 slidesshapes 查找目标文本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from pptx import Presentation

prs = Presentation("existing.pptx")

# 遍历所有幻灯片和形状
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_text_frame:
for paragraph in shape.text_frame.paragraphs:
for run in paragraph.runs:
if "旧文本" in run.text:
run.text = run.text.replace("旧文本", "新文本")

prs.save("modified.pptx")

使用模板

基于企业模板生成 PPT,通过加载 .pptx 文件保留母版和布局:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from pptx import Presentation
from pptx.util import Inches

# 加载模板
prs = Presentation("company_template.pptx")

# 使用模板中的布局
slide = prs.slides.add_slide(prs.slide_layouts[1])

# 设置标题
title = slide.shapes.title
title.text = "季度汇报"

# 设置内容
body = slide.placeholders[1]
body.text = "本季度主要工作:"

tf = body.text_frame
p = tf.add_paragraph()
p.text = "完成项目 A 的开发与上线"
p.level = 1

p = tf.add_paragraph()
p.text = "启动项目 B 的需求分析"
p.level = 1

prs.save("quarterly_report.pptx")

验证

生成 PPT 后,通过以下方式验证:

  1. 直接打开:用 PowerPoint 或 WPS 打开生成的 .pptx 文件,检查内容与样式

  2. 检查幻灯片数量:通过遍历幻灯片和形状数量,确认文件生成是否正确:

1
2
3
4
5
6
7
from pptx import Presentation

prs = Presentation("demo.pptx")
print(f"幻灯片数量: {len(prs.slides)}")

for i, slide in enumerate(prs.slides):
print(f"第 {i + 1} 页,包含 {len(slide.shapes)} 个形状")
  1. 提取文本验证内容:遍历所有形状提取文本,确认内容已写入:
1
2
3
4
5
6
7
from pptx import Presentation

prs = Presentation("demo.pptx")
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_text_frame:
print(shape.text_frame.text)

总结

步骤清单

  1. pip install python-pptx 安装依赖
  2. 创建 Presentation() 实例或加载模板
  3. 使用 slide_layouts 添加幻灯片
  4. 通过 shapes 添加文本框、图片、表格、图表
  5. 使用 fontfillline 设置样式
  6. 调用 save() 保存文件

注意事项

  • 布局索引从 0 开始,0 是标题页,6 是空白页
  • 图片路径使用绝对路径或相对于脚本的路径
  • 字体名称需与系统中已安装的字体一致,否则会回退到默认字体
  • 修改已有 PPT 时,布局受限于模板的母版设计
  • python-pptx 仅支持 .pptx 格式,不支持旧版 .ppt

方法速查

功能 方法
创建 PPT Presentation()
添加幻灯片 prs.slides.add_slide(prs.slide_layouts[n])
添加文本框 slide.shapes.add_textbox(left, top, width, height)
添加图片 slide.shapes.add_picture(path, left, top, width, height)
添加表格 slide.shapes.add_table(rows, cols, left, top, width, height)
添加图表 slide.shapes.add_chart(chart_type, left, top, width, height, data)
添加形状 slide.shapes.add_shape(shape_type, left, top, width, height)
保存文件 prs.save(path)