Charts from Excel to PowerPoint with Python

ぃ、小莉子 提交于 2019-11-28 23:54:22

After spending hours of trying different things, I have found the solution to this problem. Hopefully,it will help someone save some time.The following code will copy all the charts from "workbook_with_charts.xlsx" to "Final_PowerPoint.pptx."

For some reason, that I am yet to understand, it works better when running this Python program from CMD terminal. It sometimes breaks down if you tried to run this several times, even though the first run is usually OK.

Another issue is that in the fifth line, if you make False using "presentation=PowerPoint.Presentations.Add(False)," it does not work with Microsoft Office 2013, even though both "True" and "False" will still work with Microsoft Office 2010.

It would be great if someone can clarify these about two issues.

# importing the necessary libraries
import win32com.client
from win32com.client import constants

PowerPoint=win32com.client.Dispatch("PowerPoint.Application")
Excel=win32com.client.Dispatch("Excel.Application")


presentation=PowerPoint.Presentations.Add(True)
workbook=Excel.Workbooks.Open(Filename="C:\\.........\\workbook_with_charts.xlsx",ReadOnly=1,UpdateLinks=False)

for ws in workbook.Worksheets:
    for chart in ws.ChartObjects():
    # Copying all the charts from excel
        chart.Activate()
        chart.Copy()  

        Slide=presentation.Slides.Add(presentation.Slides.Count+1,constants.ppLayoutBlank)
        Slide.Shapes.PasteSpecial(constants.ppPasteShape)

    # WE are going to make the title of slide the same chart title
    # This is optional 
    textbox=Slide.Shapes.AddTextbox(1,100,100,200,300)
    textbox.TextFrame.TextRange.Text=str(chart.Chart.ChartTitle.Text)

presentation.SaveAs("C:\\...........\\Final_PowerPoint.pptx")
presentation.Close()
workbook.Close()

print 'Charts Finished Copying to Powerpoint Presentation'

Excel.Quit()
PowerPoint.Quit()

The approach I'd be inclined toward with the current python-pptx version is to read the Excel sheets for their data and recreate the charts in python-pptx. That of course would require knowing what the chart formatting is, etc., so I could see why you might not want to do that.

Importing charts directly from Excel has been done in the past, see the pull request here on GitHub: https://github.com/scanny/python-pptx/pull/65

But it involved a large amount of surgery on python-pptx, and many versions back now, so at most it might be a good guide to what strategies might work. You'd need to want it pretty bad I suppose to go that route :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!