Skip to main content
Practice

Automating PPT Tasks with Python

In this lesson, we will introduce how to handle PPT tasks with Python and how to add tables and charts using data.

Of course, creating simple slides manually is faster, but when dealing with large scale data and repetitive tasks, using a Python program is much more efficient.

As previously mentioned, you don't need to try to understand the code yet!

All code is written, explained, and improved by AI. πŸ™‚

Press the β–ΆοΈŽ Run button highlighted in green in the code editor and lightly read through the code explanation below!


Light Code Explanation​

If you're curious about how the code works in general, please refer to the following.


1. Preparing Participant Data​

Prepare the data consisting of Participant Name, Registration Date, Gender, and Age as follows.

Participant Data
# Define participant data
csv_data = [
["Participant Name", "Registration Date", "Gender", "Age"],
["John Doe", "2024-09-01", "Male", "25"],
["Jane Smith", "2024-09-02", "Female", "30"],
["Michael Brown", "2024-09-03", "Male", "35"],
["Chris Johnson", "2024-09-04", "Male", "42"],
["Emily Davis", "2024-09-05", "Female", "28"],
["Sarah Wilson", "2024-09-06", "Female", "39"],
["David Lee", "2024-09-07", "Male", "24"],
]

The purpose of the program is to generate 2 slides based on the data below.

  • Slide 1: Display the participant list in a table format

  • Slide 2: Visualize the gender distribution as a pie chart (XL_CHART_TYPE.PIE) and age group distribution as a bar chart (XL_CHART_TYPE.COLUMN_CLUSTERED)


2. Converting CSV Data to Python Variable​

The following code saves the participant list to the participants variable based on the defined data.

Create Participant List
# Variable to hold the participant list
participants = []

# Use a loop to save participant information to the participants variable
for row in csv_data[1:]:
participants.append({
"name": row[0],
"date": row[1],
"gender": row[2],
"age": int(row[3])
})

3. Creating a PowerPoint File​

Now let's create a PowerPoint file and add slides.

Create PowerPoint File
# Import the Presentation function from the python-pptx library
from pptx import Presentation

# Create a PowerPoint file
prs = Presentation()

# Select slide layout
slide_layout = prs.slide_layouts[5]

# Add a slide
slide = prs.slides.add_slide(slide_layout)

# Add slide title
title = slide.shapes.title

# Enter slide title
title.text = "Startup Event Participants"

Executing this code will create a slide with the title "Startup Event Participants."


4. Display Participant Information in a Table​

You can add participant information to the slide in a table format using a loop as follows.

Add Participant Information to Slide as Table
# Add a table using the add_table function
table = slide.shapes.add_table(len(participants) + 1, 4, Inches(0.5), Inches(1.5), Inches(8), Inches(3)).table

# Add table header
for col_index, heading in enumerate(csv_data[0]):
table.cell(0, col_index).text = heading

# Add participant information
for row_index, participant in enumerate(participants, start=1):
table.cell(row_index, 0).text = participant["name"]
table.cell(row_index, 1).text = participant["date"]
table.cell(row_index, 2).text = participant["gender"]
table.cell(row_index, 3).text = str(participant["age"])

5. Data Visualization: Adding a Gender Distribution Chart​

Now let's visualize the gender distribution with a pie chart.

Add Gender Distribution Pie Chart
# Import the Counter function from the collections library
from collections import Counter

# Import the ChartData function from the pptx.chart.data library
from pptx.chart.data import ChartData

# Import the XL_CHART_TYPE function from the pptx.enum.chart library
from pptx.enum.chart import XL_CHART_TYPE

# Pie chart data
gender_count = Counter(p["gender"] for p in participants)

# Create chart data using the ChartData function
chart_data = ChartData()

# Add chart data
chart_data.categories = list(gender_count.keys())

# Add chart data series
chart_data.add_series('Gender Distribution', (gender_count["Male"], gender_count["Female"]))

# Add the pie chart
chart = slide.shapes.add_chart(XL_CHART_TYPE.PIE, Inches(0.5), Inches(1.5), Inches(4), Inches(3), chart_data).chart

The gender distribution of participants is now automatically rendered as a pie chart.


6. Data Visualization: Adding an Age Group Bar Chart​

Group participants' ages into their 20s, 30s, and 40s to draw a bar chart.

Add Age Group Distribution Bar Chart
# Save the number of participants by age group in the age_groups variable
age_groups = {'20s': 0, '30s': 0, '40s': 0}

# Create age group distribution data
for participant in participants:
age = participant["age"]
if 20 <= age < 30:
age_groups['20s'] += 1
elif 30 <= age < 40:
age_groups['30s'] += 1
elif 40 <= age < 50:
age_groups['40s'] += 1

# Create chart data using the CategoryChartData function
bar_chart_data = CategoryChartData()

# Add chart data
bar_chart_data.categories = list(age_groups.keys())

# Add the bar chart
bar_chart_data.add_series('Age Group Distribution', tuple(age_groups.values()))

# Add the bar chart
chart = slide.shapes.add_chart(XL_CHART_TYPE.COLUMN_CLUSTERED, Inches(5), Inches(1.5), Inches(4), Inches(3), bar_chart_data).chart

7. Saving the pptx File​

Finally, the following code saves the work as a pptx file.

Save pptx File
# Save the file as output_file.pptx
prs.save("output_file.pptx")

As mentioned earlier, to check the code work in the CodeFriends practice screen, be sure to name the file output_file!


Did you get the hang of how to create a PPT with Python code?

In the next lesson, we will experience creating a docx document using Python.