Automating PowerPoint With Python-pptx

In daily work, we always need to create or modify PPT. But you can also use Python to create or modify PPT files. This article will tell you how to use the Python-pptx module to generate ppt automatically or with a PPT template and how to modify the existing PPT with examples.

1. The Python Module python-pptx.

  1. The python-pptx is a library for Python to process ppt files. It focuses on reading and writing, cannot be exported, and has no rendering function.
  2. Before you can use the python-pptx module, you need to run the command pip3 install -i https://pypi.doubanio.com/simple/python-pptx in a terminal to install it.
    $ pip3 install -i https://pypi.doubanio.com/simple/ python-pptx
    Looking in indexes: https://pypi.doubanio.com/simple/
    Collecting python-pptx
      Downloading https://pypi.doubanio.com/packages/eb/c3/bd8f2316a790291ef5aa5225c740fa60e2cf754376e90cb1a44fde056830/python-pptx-0.6.21.tar.gz (10.1 MB)
         |████████████████████████████████| 10.1 MB 2.1 MB/s            
      Preparing metadata (setup.py) ... done
    Requirement already satisfied: lxml>=3.1.0 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from python-pptx) (4.6.2)
    Requirement already satisfied: Pillow>=3.3.2 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from python-pptx) (9.0.1)
    Requirement already satisfied: XlsxWriter>=0.5.7 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from python-pptx) (1.3.7)
    Using legacy 'setup.py install' for python-pptx, since package 'wheel' is not installed.
    Installing collected packages: python-pptx
        Running setup.py install for python-pptx ... done
    Successfully installed python-pptx-0.6.21
    
  3. Run the command pip show python-pptx in the terminal to confirm the installation.
    $ pip show python-pptx
    Name: python-pptx
    Version: 0.6.21
    Summary: Generate and manipulate Open XML PowerPoint (.pptx) files
    Home-page: http://github.com/scanny/python-pptx
    Author: Steve Canny
    Author-email: [email protected]
    License: The MIT License (MIT)
    Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
    Requires: lxml, Pillow, XlsxWriter
    Required-by:

2. How To Use python-pptx Module To Create A PPT With Simple Text.

  1. The below example source code will create a PPT using the python-pptx module.
  2. It will also set the PPT title and subtitle text, and then save it to a pptx file.
    # Import the Presentation class from the pptx module.
    from pptx import Presentation
    
    # Create an instance of the Presentation class.
    prs = Presentation()
    # Create the title slide.
    title_slide_layout = prs.slide_layouts[0]
    # Add the title slide to the PPT slides array.
    slide = prs.slides.add_slide(title_slide_layout)
    
    # Get the PPT title object.
    title = slide.shapes.title
    # Get the PPT subtitle object.
    subtitle = slide.placeholders[1]
    
    # Set the PPT title.
    title.text = "Hello python-pptx Module!"
    # Set the PPT title slide sub title.
    subtitle.text = "pip install python-pptx"
    
    # Save the PPT to a .pptx file.
    prs.save("test.pptx")
    

3. How To Use python-pptx Module To Add Chart To A PPT File.

  1. The below source code can create a chart and add it to the output PPT file.
    # Import the Presentation class from the pptx module.
    from pptx import Presentation
    # Import the ChartData class form the pptx.chart.data package.
    from pptx.chart.data import ChartData
    # Import the chart type constants variable.
    from pptx.enum.chart import XL_CHART_TYPE
    # Import the units type.
    from pptx.util import Inches
    
    # Create the Presentation object to build the PPT file.
    prs = Presentation()
    # Add a slide to the PPT file.
    slide = prs.slides.add_slide(prs.slide_layouts[5])
    
    # Create the ChartData object to save the chart data.
    chart_data = ChartData()
    # Save the categories data in an array, the categories data will be displayed in the horizontal x axis .
    chart_data.categories = ['Java', 'Python', 'JavaScript']
    # Save the series data in a tuple, the series data will be displayed in the vertial y axis.
    chart_data.add_series('Series 1', (19.2, 21.4, 16.7))
    
    # Define the x, y axis unit.
    x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)
    
    # Add the column chart to the PPT slide.
    slide.shapes.add_chart(
      XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data
    )
    
    # Save the PPT file.
    prs.save('chart-01.pptx')

4. How To Use PPT Template To Generate PPT File With Python-pptx Module.

  1. Prepare a ppt template file ( you can download one from the internet or create a template PPT file by yourself).
  2. Load the PPT template file and use the specified slide style in your python source code using the python-pptx module.
  3. Add data to the PPT template file and generate a new PPT file.
  4. Below is the example source code.
    # Import the pptx module Presentation class.
    from pptx import Presentation
    
    # Import the pptx x axis unit.
    from pptx.util import Inches
    from pptx.util import Cm #Inches
    # Import the ChartData class.
    from pptx.chart.data import ChartData
    
    # Import the Chart type XL_CHART_TYPE.
    from pptx.enum.chart import XL_CHART_TYPE
    from pptx.enum.chart import XL_LEGEND_POSITION
    
    if __name__ == '__main__':
      # Create the Presentation object based on the template PPT file.
      prs = Presentation('template.pptx')
      # Add the first slide, title only slide.
      title_only_slide_layout = prs.slide_layouts[5]
      slide = prs.slides.add_slide(title_only_slide_layout)
      shapes = slide.shapes
    
      # Set the slide title text
      shapes.title.text = 'Report'
    
      # Define the chart table data in an array.
      name_objects = ["object1", "object2", "object3"]
      name_AIs = ["AI1", "AI2", "AI3"]
      val_AI1 = (19.2, 21.4, 16.7)
      val_AI2 = (22.3, 28.6, 15.2)
      val_AI3 = (20.4, 26.3, 14.2)
      val_AIs = [val_AI1, val_AI2, val_AI3]
    
      # Define the chart table style.
      rows = 4
      cols = 4
      top  = Cm(12.5)
      left  = Cm(3.5) #Inches(2.0)
      width = Cm(24) # Inches(6.0)
      height = Cm(6) # Inches(0.8)
    
      # Add the chart table to the slide.
      table = shapes.add_table(rows, cols, left, top, width, height).table
    
      # Set the table column width.
      table.columns[0].width = Cm(6)# Inches(2.0)
      table.columns[1].width = Cm(6)
      table.columns[2].width = Cm(6)
      table.columns[3].width = Cm(6)
    
      # Set the table text row.
      table.cell(0, 1).text = name_objects[0]
      table.cell(0, 2).text = name_objects[1]
      table.cell(0, 3).text = name_objects[2]
    
      # Fill data to the table.
      table.cell(1, 0).text = name_AIs[0]
      table.cell(1, 1).text = str(val_AI1[0])
      table.cell(1, 2).text = str(val_AI1[1])
      table.cell(1, 3).text = str(val_AI1[2])
    
      table.cell(2, 0).text = name_AIs[1]
      table.cell(2, 1).text = str(val_AI2[0])
      table.cell(2, 2).text = str(val_AI2[1])
      table.cell(2, 3).text = str(val_AI2[2])
    
      table.cell(3, 0).text = name_AIs[2]
      table.cell(3, 1).text = str(val_AI3[0])
      table.cell(3, 2).text = str(val_AI3[1])
      table.cell(3, 3).text = str(val_AI3[2])
    
      # Define the ChartData object.
      chart_data = ChartData()
      chart_data.categories = name_objects
      chart_data.add_series(name_AIs[0], val_AI1)
      chart_data.add_series(name_AIs[1], val_AI2)
      chart_data.add_series(name_AIs[2], val_AI3)
    
      # Add the chart to the PPT file.
      x, y, cx, cy = Cm(3.5), Cm(4.2), Cm(24), Cm(8)
    
      graphic_frame = slide.shapes.add_chart(
        XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data
        )
    
      chart = graphic_frame.chart
    
      chart.has_legend = True
      chart.legend.position = XL_LEGEND_POSITION.TOP
      chart.legend.include_in_layout = False
    
      value_axis = chart.value_axis
      value_axis.maximum_scale = 100.0
    
      value_axis.has_title = True
      value_axis.axis_title.has_text_frame = True
      value_axis.axis_title.text_frame.text = "False positive"
      value_axis.axis_title.text_frame.auto_size
      # Save a new PPT file based on the template.
      prs.save('test_template.pptx')
    

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.