Automating PowerPoint with Python: win32com, python-pptx, and seaborn
This tutorial demonstrates how to use Python libraries such as win32com and python-pptx to automate PowerPoint creation, manipulation, and styling—including copying templates, adding slides, text boxes, tables, charts, shapes, and images—while also covering seaborn installation and basic data‑visualization examples that can be embedded into PPT files.
1. What PPT Automation Can Do
Python can automatically generate PowerPoint files, reduce formatting time, ensure consistent report styles, and greatly improve work efficiency.
2. Using win32com to Operate PPT
Install the library:
pip install pypiwin32Example of copying a template slide:
import win32com
from win32com.client import Dispatch
import os
ppt = Dispatch('PowerPoint.Application')
ppt.Visible = 1
ppt.DisplayAlerts = 0
pptSel = ppt.Presentations.Open(os.getcwd() + "\\2.2 win32 ppt测试.pptx")
pptSel.Slides(1).Copy()
pageNums = 10
for i in range(pageNums):
pptSel.Slides.Paste()
pptSel.SaveAs(os.getcwd() + "\\win32_copy模板.pptx")
pptSel.Close()
ppt.Quit()3. python-pptx for PPT Creation and Manipulation
Install the library:
pip install python-pptx3.1 Create a New PPT and Add Slides
from pptx import Presentation
ppt = Presentation()
slide = ppt.slides.add_slide(ppt.slide_layouts[0])
ppt.save('new_ppt.pptx')3.2 Delete Slides
from pptx import Presentation
def del_slide(prs, index):
slides = list(prs.slides._sldIdLst)
prs.slides._sldIdLst.remove(slides[index])
ppt = Presentation('python-pptx 多页待删除模板.pptx')
number_pages = len(ppt.slides)
print('Before:', number_pages)
for _ in range(3):
del_slide(ppt, 0)
print('After:', len(ppt.slides))
ppt.save('python-pptx 多页已删除模板.pptx')3.3 Add Text Boxes and Style Them
from pptx import Presentation
from pptx.util import Cm, Pt
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN, MSO_VERTICAL_ANCHOR
ppt = Presentation('template.pptx')
slide = ppt.slides[0]
left, top, width, height = Cm(16.9), Cm(1), Cm(12), Cm(1.2)
textBox = slide.shapes.add_textbox(left, top, width, height)
textBoxFill = textBox.fill
textBoxFill.solid()
textBoxFill.fore_color.rgb = RGBColor(187, 255, 255)
line = textBox.line
line.color.rgb = RGBColor(0, 255, 0)
line.width = Cm(0.1)
tf = textBox.text_frame
tf.paragraphs[0].text = '这是一段文本框里的文字'
tf.paragraphs[0].font.size = Pt(20)
tf.paragraphs[0].font.bold = True
tf.paragraphs[0].font.italic = True
tf.paragraphs[0].font.color.rgb = RGBColor(255, 0, 0)
tf.paragraphs[0].alignment = PP_ALIGN.CENTER
tf.vertical_anchor = MSO_VERTICAL_ANCHOR.BOTTOM
ppt.save('styled_textbox.pptx')3.4 Add Tables and Style Cells
from pptx import Presentation
from pptx.util import Cm, Pt
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN, MSO_ANCHOR
ppt = Presentation('template.pptx')
slide = ppt.slides[0]
left, top, width, height = Cm(6), Cm(12), Cm(13.6), Cm(5)
shape = slide.shapes.add_table(6, 7, left, top, width, height)
table = shape.table
# Set column widths, merge header cells, fill data, and apply styles (omitted for brevity)
ppt.save('styled_table.pptx')3.5 Add Charts
from pptx import Presentation
from pptx.util import Cm, Pt
from pptx.chart.data import ChartData
from pptx.enum.chart import XL_CHART_TYPE
ppt = Presentation('template.pptx')
slide = ppt.slides[0]
chart_data = ChartData()
chart_data.categories = ['4/30-5/14', '5/15-5/21', '5/22-6/28']
chart_data.add_series('问题总数', (22, 32, 37))
left, top, width, height = Cm(6), Cm(10), Cm(16.1), Cm(7.5)
chart = slide.shapes.add_chart(XL_CHART_TYPE.LINE, left, top, width, height, chart_data).chart
chart.has_legend = True
chart.font.size = Pt(10)
ppt.save('styled_chart.pptx')3.6 Add Shapes and Customize Appearance
from pptx import Presentation
from pptx.util import Cm
from pptx.dml.color import RGBColor
from pptx.enum.shapes import MSO_SHAPE
ppt = Presentation('template.pptx')
slide = ppt.slides[0]
left, top, width, height = Cm(2.5), Cm(4.5), Cm(30), Cm(0.5)
rect = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, left, top, width, height)
rect.fill.solid()
rect.fill.fore_color.rgb = RGBColor(34, 134, 165)
rect.line.color.rgb = RGBColor(34, 134, 165)
# Additional shapes (triangles, arrows) with text boxes omitted for brevity
ppt.save('styled_shapes.pptx')4. seaborn: Introduction and Usage
seaborn is a Python data‑visualization library built on Matplotlib that provides a high‑level interface for attractive statistical graphics.
Installation:
pip install seabornBasic example – line plot using relplot :
import matplotlib.pyplot as plt
import seaborn as sns
data = sns.load_dataset('fmri')
sns.relplot(x='timepoint', y='signal', kind='line', data=data, ci=None)
plt.show()Line plot using lineplot with confidence interval:
sns.lineplot(x='timepoint', y='signal', data=data, ci=95)
plt.show()Multiple subplots example:
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
sns.lineplot(x='timepoint', y='signal', data=data, ci=None, ax=axes[0])
sns.lineplot(x='timepoint', y='signal', hue='region', style='event', data=data, ci=None, ax=axes[1])
plt.show()Saving the figure before plt.show() :
plt.savefig('seaborn_plot.png')
plt.show()Scatter plot with hue, style, and size:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
sns.relplot(x='total_bill', y='tip', data=tips, hue='sex', style='smoker', size='size')
plt.show()Bar plot (vertical and horizontal):
import seaborn as sns
import matplotlib.pyplot as plt
x = ['金融', '农业', '制造业', '新能源']
y = [164, 86, 126, 53]
sns.barplot(x=x, y=y)
plt.show()
# Horizontal version
sns.barplot(y=x, x=y)
plt.show()5. Inserting Images into PowerPoint
After generating a seaborn figure, insert it into a slide:
from pptx import Presentation
from pptx.util import Cm
ppt = Presentation('template.pptx')
slide = ppt.slides[0]
left, top, width, height = Cm(6), Cm(6), Cm(20), Cm(9)
slide.shapes.add_picture('seaborn_plot.png', left, top, width, height)
ppt.save('ppt_with_image.pptx')6. Reading Data from Existing PPT
Example that prints all shape types and extracts table cell text:
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
ppt = Presentation('report.pptx')
slide0 = ppt.slides[0]
for shape in slide0.shapes:
print(shape.shape_type)
if shape.shape_type == MSO_SHAPE_TYPE.TABLE:
for row in shape.table.rows:
for cell in row.cells:
print(cell.text_frame.text)This script demonstrates how to read and later modify PPT content programmatically.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.