2

I have the below code for creating ppt out of dataframes:

Below is a snippet of the code for 3 slides:

title_slide_layout = prs.slide_layouts[1]
slide = prs.slides.add_slide(title_slide_layout)
slide2 = prs.slides.add_slide(title_slide_layout)
slide3 = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
title.text = "Summary Table"
title2 = slide2.shapes.title
title2.text = "New Table"
title3 = slide3.shapes.title
title3.text = "Old Table"

Since i have to create multiple such slides is there anyway to use loops and create multiple slides instead of creating it one by one manually?

Also, I am writing dataframes to slides like this:

df_to_table(slide, df1, left, top, width, height)
df_to_table(slide2, df2, left, top, width, height)
df_to_table(slide3, df3, left, top, width, height)

Is there anyway to loop this too?

Node: My code is working fine without any issues, just want to limit the lines of code for repetitive tasks.

RSM
  • 645
  • 10
  • 25

2 Answers2

1

Not sure fully but you may try like this:

slide = ["slide" + str(num1)  for num1 in range(1,4)] 
df = ["df" + str(num1)  for num1 in range(1,4)]

for i in range(0,3):
    df_to_table(slide[i], df[i], left, top, width, height)
  • I guess slide option does not work in for loop. I am getting : `AttributeError: 'str' object has no attribute 'shape'` – RSM Dec 24 '19 at 06:43
  • Here (The way I write) "slide" is a list object so shape will not work. But you will able to to iterate in the index of the list. right? – Md Ziaul Haque Dec 24 '19 at 09:27
  • I made a bit of change in your code and now it works fine: `list_of_datasets = [df1, df2, df3] list_of_slides = [slide1, slide2, slide3] # for i in list_of_datasets: # for j in list_of_slides: # df_to_table(j, i, left, top, width, height) for i, j in zip(list_of_datasets, list_of_slides): df_to_table(j, i, left, top, width, height) ` Thanks for your help. – RSM Dec 26 '19 at 03:20
1

This is what functions are for, to abstract some repetative task down to a (function) call:

def add_slide(prs, layout, title):
    """Return slide newly added to `prs` using `layout` and having `title`."""
    slide = prs.slides.add_slide(layout)
    slide.shapes.title.text = title
    return slide


title_slide_layout = prs.slide_layouts[1]
slide = add_slide(prs, title_slide_layout, "Summary Table")
slide2 = add_slide(prs, title_slide_layout, "New Table")
slide3 = add_slide(prs, title_slide_layout, "Old Table")

Your second question is an entirely different question and I recommend you ask it separately. StackOverflow is designed around a one-question-at-a-time format.

scanny
  • 26,423
  • 5
  • 54
  • 80
  • thanks for your answer. please see another question: https://stackoverflow.com/q/59496023/6389099 – RSM Dec 27 '19 at 05:09