Skip to main content
Practice

Creating and Managing Tables in Slides with Python

Manually entering values for each item when creating a table in a PowerPoint slide from an Excel file can be a tedious task.

By using the python-pptx library, you can easily create and manage tables with Python code.

By taking advantage of the benefits of automating repetitive tasks, you can efficiently insert multiple tables into slides after processing large data sets with Python.


Inserting Tables: The First Step in Organizing Data

To insert a table in a slide, use the add_table() method.

The parameters of the add_table method are as follows:

  • rows : The number of rows in the table

  • cols : The number of columns in the table

  • left : The distance from the left edge of the table

  • top : The distance from the top edge of the table

  • width : The width of the table

  • height : The height of the table


Code Example

Inserting a Table
# Define the number of rows and columns
rows = 2
cols = 2

# Define the position of the table
left = Inches(2)
top = Inches(2)

# Define the size of the table
width = Inches(4)
height = Inches(1.5)

# Add the table to the slide
table = slide.shapes.add_table(rows, cols, left, top, width, height).table

# Add text to the first row, first column
table.cell(0, 0).text = "Header 1"

# Add text to the first row, second column
table.cell(0, 1).text = "Header 2"

# Add text to the second row, first column
table.cell(1, 0).text = "Row 1, Col 1"

# Add text to the second row, second column
table.cell(1, 1).text = "Row 1, Col 2"

The code above uses the slide.shapes.add_table(rows, cols, left, top, width, height) method to add a table and assigns the table object to the table variable.

Using the cell method of the table object assigned to the table variable, you can add text to specific cells in the table.

The parameter format is table.cell(row, col).text = "Content", where row is the row number, col is the column number, and Content represents the text to be added to the cell.


Merging Cells

When using tables, there may be times when you need to merge multiple cells into one or split a merged cell. In python-pptx, you can use the merge() method to merge cells.

Merging Cells
# Example of merging cells
table.cell(0, 0).merge(table.cell(0, 1))

# Add text to the merged cell
table.cell(0, 0).text = "Merged Header"

Note that python-pptx does not directly provide a feature to split cells.

Therefore, if cell splitting is necessary, you will need to recreate the table.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.