Psychology
November 18, 2026
9 min read

Automate PowerPoint with Python: python-pptx Guide

Learn PowerPoint automation with Python: build decks with python-pptx, fill templates, add charts and tables from pandas, one slide per row. Code included.

If you build the same weekly report, client deck or per-customer summary by hand, you can generate it with Python instead. The python-pptx library creates and edits .pptx files without PowerPoint installed, so the same script works on a laptop, a server or a scheduled job. This guide walks through PowerPoint automation with Python from install to a deck with one slide per row of data, and every snippet runs as shown.

What you will build

  • A deck from scratch: title slide, bullet slide, text box and picture
  • Slides filled from a template's layouts and placeholders
  • A chart and a table built from a pandas DataFrame
  • One slide per row of data, saved to a .pptx file

The snippets are written to be pasted into one script, in order, sharing the same prs object. The template-listing snippet is the one exception: it is a standalone inspection step you can run separately.

Install python-pptx

You need a recent Python 3. The package is called python-pptx on PyPI, but you import it as pptx. We also install pandas for the data examples and matplotlib to create a sample image.

pip install python-pptx pandas matplotlib

Create a presentation from scratch

A Presentation() with no arguments starts from python-pptx's built-in default template. You pick a slide layout by index: 0 is Title Slide, 1 is Title and Content, 5 is Title Only and 6 is Blank. Each add_slide() call returns a slide whose placeholders you can fill.

from pptx import Presentation
from pptx.util import Inches, Pt

prs = Presentation()  # default template, 4:3, 10 x 7.5 inches

# Slide 1: title slide (layout 0 = Title Slide)
slide = prs.slides.add_slide(prs.slide_layouts[0])
slide.shapes.title.text = "Q4 Sales Report"
slide.placeholders[1].text = "Generated with python-pptx"

# Slide 2: title and bullets (layout 1 = Title and Content)
slide = prs.slides.add_slide(prs.slide_layouts[1])
slide.shapes.title.text = "Highlights"
tf = slide.placeholders[1].text_frame
tf.text = "Revenue grew in every region"
p = tf.add_paragraph()
p.text = "Strongest growth in the north"
p.level = 1
p = tf.add_paragraph()
p.text = "Two new customers signed in December"

# Slide 3: blank layout (6) with a text box and a picture
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(4, 3))
ax.plot([1, 2, 3, 4], [3, 5, 4, 8])
fig.savefig("trend.png", dpi=150, bbox_inches="tight")
plt.close(fig)

slide = prs.slides.add_slide(prs.slide_layouts[6])
box = slide.shapes.add_textbox(Inches(0.5), Inches(0.5), Inches(9), Inches(1))
box.text_frame.text = "A matplotlib image on a slide"
box.text_frame.paragraphs[0].runs[0].font.size = Pt(28)
box.text_frame.paragraphs[0].runs[0].font.bold = True
slide.shapes.add_picture("trend.png", Inches(2.5), Inches(2), width=Inches(5))

Sizes in python-pptx are stored in EMU (English Metric Units). Use Inches(), Cm() or Pt() from pptx.util instead of raw numbers. The default template is 4:3 (10 by 7.5 inches), so the coordinates in this guide fit that page.

Fill a template's placeholders

For real work you will usually start from your company template: create it in PowerPoint with the layouts you want, then open it with Presentation("template.pptx"). The first job is to find out what each layout contains.

List layouts and placeholder indexes

from pptx import Presentation

prs = Presentation()  # or Presentation("template.pptx")

for i, layout in enumerate(prs.slide_layouts):
    print(i, layout.name)
    for ph in layout.placeholders:
        print("   idx", ph.placeholder_format.idx,
              ph.placeholder_format.type, ph.name)

Every placeholder has an idx. Title placeholders are usually 0 and the main body is usually 1, but your template may differ, so check the printout and do not guess.

Fill the placeholders

Looking a layout up by name is safer than by position, because a designer may reorder layouts later. This continues the same prs:

layout = next(l for l in prs.slide_layouts if l.name == "Title and Content")
slide = prs.slides.add_slide(layout)

for ph in slide.placeholders:
    idx = ph.placeholder_format.idx
    if idx == 0:
        ph.text = "Filled from a template layout"
    elif idx == 1:
        ph.text_frame.text = "Placeholder idx 1 holds the body text"

Two details save time. First, any sample slides already inside your template stay in the file, so delete them or start from a template with none. Second, a picture placeholder is a different type: call placeholder.insert_picture("logo.png") on it instead of setting .text.

Add a chart and a table from a pandas DataFrame

Charts in python-pptx are native PowerPoint charts, not images, so people can still edit the data in PowerPoint. You describe the data with CategoryChartData and pass it to add_chart(). Convert DataFrame columns with .tolist() so you hand python-pptx plain Python numbers.

A chart

import pandas as pd
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE, XL_LEGEND_POSITION

df = pd.DataFrame({
    "Month": ["Oct", "Nov", "Dec"],
    "Revenue": [120, 135, 160],
    "Costs": [90, 95, 100],
})

slide = prs.slides.add_slide(prs.slide_layouts[5])  # Title Only
slide.shapes.title.text = "Revenue vs costs"

chart_data = CategoryChartData()
chart_data.categories = df["Month"].tolist()
chart_data.add_series("Revenue", df["Revenue"].tolist())
chart_data.add_series("Costs", df["Costs"].tolist())

graphic_frame = slide.shapes.add_chart(
    XL_CHART_TYPE.COLUMN_CLUSTERED,
    Inches(0.5), Inches(1.5), Inches(9), Inches(5.5),
    chart_data,
)
chart = graphic_frame.chart
chart.has_legend = True
chart.legend.position = XL_LEGEND_POSITION.BOTTOM
chart.legend.include_in_layout = False

For other shapes use a different XL_CHART_TYPE, such as LINE_MARKERS, BAR_CLUSTERED or PIE. Pie charts take a single series.

A table

A table needs one extra row for the header. The loop writes the column names first, then each DataFrame value as a string.

slide = prs.slides.add_slide(prs.slide_layouts[5])
slide.shapes.title.text = "The numbers"

n_rows, n_cols = df.shape
table_shape = slide.shapes.add_table(
    n_rows + 1, n_cols, Inches(0.5), Inches(1.7), Inches(9), Inches(0.5) * (n_rows + 1)
)
table = table_shape.table

for j, col in enumerate(df.columns):
    table.cell(0, j).text = str(col)

for i in range(n_rows):
    for j in range(n_cols):
        table.cell(i + 1, j).text = str(df.iat[i, j])

The table gets the template's default table style. To control fonts or fills, set them per cell, for example with cell.text_frame.paragraphs[0].font.size or cell.fill.

Generate one slide per row of data

This is where automation pays off. Loop over a DataFrame (or a CSV, or the result of a database query) and add one slide per record. The same pattern produces a per-customer summary, a per-branch report or a per-student certificate.

regions = pd.DataFrame({
    "Region": ["North", "South", "Center"],
    "Sales": [182000, 143500, 251300],
    "Target": [170000, 150000, 240000],
    "Owner": ["Dana", "Avi", "Noa"],
})

for _, row in regions.iterrows():
    slide = prs.slides.add_slide(prs.slide_layouts[5])
    slide.shapes.title.text = f"{row['Region']} region"

    box = slide.shapes.add_textbox(Inches(0.8), Inches(2), Inches(8.4), Inches(3))
    tf = box.text_frame
    tf.word_wrap = True
    tf.text = f"Sales: {row['Sales']:,}"
    for line in (
        f"Target: {row['Target']:,}",
        f"Vs target: {row['Sales'] - row['Target']:+,}",
        f"Owner: {row['Owner']}",
    ):
        tf.add_paragraph().text = line
    for p in tf.paragraphs:
        p.font.size = Pt(24)

Save the file

Once the script has built everything, one line writes the deck:

prs.save("report.pptx")

Open report.pptx in PowerPoint, Keynote, LibreOffice or Google Slides. If the file is open in PowerPoint when you run the script again, Windows will refuse to overwrite it, so close it first or save under a new name with a timestamp.

Common mistakes

  • Wrong placeholder index. Print the layout's placeholders instead of assuming placeholders[1] exists.
  • Text overflow. python-pptx does not measure text. Long strings simply run off the slide, so set word_wrap = True, choose a font size that fits, or shorten the content in code.
  • NumPy types in charts. Use .tolist() on DataFrame columns, as shown above.
  • Expecting animations or SmartArt. python-pptx does not create them. Build the visual in the template and fill its text instead.
  • Overwriting an open file. Write to a new file name rather than replacing a deck someone has open.

Other ways to automate PowerPoint, and when Python is the right choice

  • VBA inside PowerPoint. Good for tweaking a deck you already have open, such as reformatting every slide or adding a button. It needs desktop PowerPoint, it runs on one machine at a time, and it is harder to pull data from databases, APIs or pandas.
  • Office Scripts. These are built mainly for Excel on the web. They are not a way to build PowerPoint slides, so they do not replace the approaches here.
  • AI assistants that write python-pptx code. Describe the deck and the data and an assistant can draft the script in seconds. It is a good way to start, but always run and check the result: generated code sometimes uses outdated or invented API names, and it cannot see how your slides look. Knowing the basics above makes those errors easy to spot and fix.

Choose Python when the content comes from data, when you need the same deck many times (weekly, per customer, per branch), when the job must run on a server or a schedule without PowerPoint, or when you want the generation step in version control. Choose VBA for one-off edits inside a single open deck. If you only build one presentation a quarter, doing it by hand is still fine.

FAQ

Can Python create a PowerPoint presentation?

Yes. The python-pptx library creates new .pptx files and edits existing ones: slides, text, tables, pictures and native charts. PowerPoint does not need to be installed.

Is python-pptx free?

Yes, it is open source and installs with pip install python-pptx.

Can I edit an existing PowerPoint with Python?

Yes. Open it with Presentation("existing.pptx"), loop over prs.slides and their shapes, change text or add content, then save under a new name. Check shape.has_text_frame before reading text from a shape.

Can I turn a PowerPoint into a PDF with Python?

Not with python-pptx alone, because it does not render slides. Convert the saved file with LibreOffice in headless mode (soffice --headless --convert-to pdf report.pptx) or with PowerPoint itself on Windows.

If you want to go from scripts like this to a data career, TovTech teaches Python and data skills in its data course.