pythonreplaceslidepresentation

Change slides' field in presentation with pyhton


I have an excel file and I would like to use these items to replace my slides, I added ABC code to replace my presentation but I can reach the title but cannot reach to paragraph.

Could you please explain how I can reach to paragraph and replace it in my presentation?

For example:

myexcel.xlsx


mypresentation.pptx

Slide 1

Slide 2


Result:

Slide 1

Slide 2


Solution

  • I used openpyxl for the Excel and python-pptx for the presentation:

    import openpyxl
    from pptx import Presentation
    
    ex = "myexcel.xlsx"
    pr = "mypresentation.pptx"
    
    # Excel with openpyxl
    wb_obj = openpyxl.load_workbook(ex)
    sheet_obj = wb_obj.active
    max_row = sheet_obj.max_row
    max_col = sheet_obj.max_column
    
    column_list = []
    row_list = []
    
    for ro in range(1, max_row + 1):
        for co in range(1, max_col + 1):
            if ro == 1:
                cell_obj = sheet_obj.cell(row = ro, column = co)
                column_list.append(cell_obj.value)
            if ro > 1:
                cell_obj = sheet_obj.cell(row = ro, column = co)
                row_list.append(cell_obj.value)
    print("Column Names:", column_list)
    print("Row text", row_list)
    
    # Presentation with python-pptx; https://python-pptx.readthedocs.io/en/latest/
    prs=Presentation(pr)
    text_runs = []
    for slide in prs.slides:
        for shape in slide.shapes:
            if not shape.has_text_frame:
                continue
            for paragraph in shape.text_frame.paragraphs:
                for run in paragraph.runs:
                    text_runs.append(run.text)
                    #print(run.text)
                    if run.text == "Title (ABC)":
                        run.text = row_list[2]
                    if run.text == "Body (The first name is ABC)":
                        run.text = "The first name is "+row_list[0]
                    if run.text == "Body (The last name is ABC)":
                        run.text = "The last name is "+row_list[1]
                prs.save('new.pptx')
                
    print("Text written in new.pptx")                    
    print("Text in old slides:",text_runs)
    

    Output, see file "new.ppt":

    Column Names: ['FirstName', 'LastName', 'Sex']
    Row text ['Tim', 'Knight', 'Man']
    Text written in new.pptx
    Text in old slides: ['Slide 1', 'Title (ABC)', 'Body (The first name is ABC)', 'Slide 2', 'Body (The last name is ABC)']