前言 在日常开发中,经常需要自动化生成报表、周报或数据汇报 PPT。 手动制作不仅耗时,还容易出错。 python-pptx 是一个纯 Python 库,无需安装 Microsoft Office,即可程序化创建和修改 .pptx 文件。 本文将从安装到实战,覆盖 python-pptx 的核心功能,帮助你快速上手自动化 PPT 生成。
依赖 安装 python-pptx:
如需生成图表,还需安装 lxml(通常已随 python-pptx 一起安装):
核心对象 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 Presentationprs = Presentation() prs = Presentation("a.pptx" ) prs.slides prs.slide_layouts prs.slide_masters prs.core_properties
Slide 单张幻灯片,是所有内容的容器。
1 2 3 4 5 6 slide = prs.slides.add_slide(prs.slide_layouts[1 ]) slide.shapes slide.placeholders slide.slide_layout slide.slide_id
SlideLayout 与 SlideMaster
SlideMaster :母版,控制全局背景、字体、配色
SlideLayout :布局,定义幻灯片中占位符的位置和类型
1 2 3 4 5 master = prs.slide_masters[0 ] layout = prs.slide_layouts[1 ] layout.name 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 shape.top shape.width shape.height shape.has_text_frame 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 tf.text = "Hello" tf.paragraphs[0 ] tf.add_paragraph() p = tf.paragraphs[0 ] p.text p.alignment p.level p.space_before p.space_after run = p.add_run() run.text = "加粗文本" run.font.bold = True 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, Emuslide.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 )) run.font.size = Pt(14 ) shape.line.width = Pt(2 ) value = Inches(1 ) print (value) print (Inches(1 ).cm) print (Cm(2.54 ).inches)
幻灯片尺寸 默认尺寸为 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 Presentationfrom pptx.util import Inchesprs = Presentation() print (prs.slide_width) print (prs.slide_width.inches) prs.slide_width = Inches(10 ) prs.slide_height = Inches(7.5 )
实现 创建 PPT 最简示例,创建一个空白演示文稿并保存:
1 2 3 4 from pptx import Presentationprs = 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 Presentationprs = Presentation() 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 Presentationfrom pptx.util import Inches, Ptprs = 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 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 Presentationfrom pptx.util import Inches, Ptfrom pptx.dml.color import RGBColorprs = 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 Presentationfrom pptx.util import Inchesprs = Presentation() slide = prs.slides.add_slide(prs.slide_layouts[6 ]) 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 Presentationfrom pptx.util import Inches, Ptfrom pptx.dml.color import RGBColorprs = Presentation() slide = prs.slides.add_slide(prs.slide_layouts[6 ]) 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 Presentationfrom pptx.util import Inchesfrom pptx.chart.data import CategoryChartDatafrom pptx.enum.chart import XL_CHART_TYPEprs = 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 )) 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_TYPEXL_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
设置形状样式 为形状添加边框、填充色,通过 fill 和 line 属性控制:
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 Presentationfrom pptx.util import Inches, Ptfrom pptx.dml.color import RGBColorprs = Presentation() slide = prs.slides.add_slide(prs.slide_layouts[6 ]) shape = slide.shapes.add_shape( 1 , 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 文件,通过遍历 slides 和 shapes 查找目标文本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 from pptx import Presentationprs = 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 Presentationfrom pptx.util import Inchesprs = 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 后,通过以下方式验证:
直接打开 :用 PowerPoint 或 WPS 打开生成的 .pptx 文件,检查内容与样式
检查幻灯片数量 :通过遍历幻灯片和形状数量,确认文件生成是否正确:
1 2 3 4 5 6 7 from pptx import Presentationprs = Presentation("demo.pptx" ) print (f"幻灯片数量: {len (prs.slides)} " )for i, slide in enumerate (prs.slides): print (f"第 {i + 1 } 页,包含 {len (slide.shapes)} 个形状" )
提取文本验证内容 :遍历所有形状提取文本,确认内容已写入:
1 2 3 4 5 6 7 from pptx import Presentationprs = Presentation("demo.pptx" ) for slide in prs.slides: for shape in slide.shapes: if shape.has_text_frame: print (shape.text_frame.text)
总结 步骤清单
pip install python-pptx 安装依赖
创建 Presentation() 实例或加载模板
使用 slide_layouts 添加幻灯片
通过 shapes 添加文本框、图片、表格、图表
使用 font、fill、line 设置样式
调用 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)