user14839799
user14839799

Reputation: 21

Exporting DataFrame to pptx using Python

I am trying to move my DataFrame I import from excel and put it on my pptx presentation slide. So far came up with following code but have hard time figuring out how to actually move the data frame I already imported to my presentation slide.

from pptx import Presentation
import pandas as pd


pr1 = Presentation()

slide1_reg = pr1.slide_layouts[5]

slide1 = pr1.slides.add_slide(slide1_reg)

title1 = slide1.shapes.title
title1.text = "slide 1"

df = pd.read_excel('data.xlsx')

print(df) #prints table from excel i need to put into the presentation

pr1.save("new.pptx")

Is there any way to move this data frame as a table to power point? Thank you for help.

 X1  X2
0   1   4
1   2   3

Upvotes: 1

Views: 13170

Answers (2)

moomima
moomima

Reputation: 1340

You can use the add_table() function: (see docs)

df = pd.DataFrame({'hi': [1, 2, 3], 'there': ['a', 'b', 'c']})
x, y, cx, cy = Inches(2), Inches(2), Inches(4), Inches(1.5)
shape = slide.shapes.add_table(3, 3, x, y, cx, cy)
table = shape.table
cell = table.cell(1, 2)
cell.text = str(df.iloc[1][2])

Upvotes: 2

user14839799
user14839799

Reputation: 21

I have managed to put the values from dataframe as a Chart using pandas and pptx:

    from pptx import Presentation
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.util import Inches
import pandas as pd

pr1 = Presentation()

slide1_reg = pr1.slide_layouts[5]

slide1 = pr1.slides.add_slide(slide1_reg)

title1 = slide1.shapes.title
title1.text = "slide 1"

df = pd.read_excel('data.xlsx')

print(df) 

chart_data = CategoryChartData()
chart_data.categories = df.iat[0,0], df.iat[1,0] #gets string categories
chart_data.add_series('YTD', (df.iat[0,1], df.iat[1,1])) #gets integer values

x, y, cx, cy = Inches(1), Inches(1), Inches(2), Inches(2.5)
slide1.shapes.add_chart(
    XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data
)

pr1.save("new2.pptx")

My new dataframe from excel looks like this:

 Unnamed: 0  a  b  c
0    dataset  4  4  4
1   dataset1  3  3  3
2         aa  2  2  2

As a result I get a chart with [dataset, dataset1] categories and series values [4, 3].

Let's imagine I have 20 categories dataset,dataset1...dataset19 and in next column I have integer values. I want to have a chart exported to pptx, do I need to use df.iat[row, column] 20 times for categories and 20 times for series to create a chart? Can I loop it somehow?

Upvotes: 1

Related Questions