Search code examples
pythonimagechartswin32comimport-from-excel

Using win32com via python to scrape excel file for chart objects and convert them to images


I am trying to scrape a .xlsx excel file for chart objects and export them as images. The only similar stackoverflow question I found was this one which attempts to do the same thing. The script, however, does not seem to work (even when I correct the syntax/methods). I am willing to get this running in either Python 2.7.9 or 3.4.0. as I have both versions running on my computer. Here is the code I am working with:

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application') 
wb = excel.Workbooks.Open(r'C:\Users\Emilyn\Desktop\chartTest.xlsx') 
excel.Visible = True
wb.Sheets("Sheet1").Select() 
wbSheetOne = wb.Sheets(1) 
wb.DisplayAlerts = False 
i = 0
    for chart in wbSheetOne.ChartObjects():
        print(chart.Name)
        chart.CopyPicture()
        excel.ActiveWorkbook.Sheets.Add(After =excel.ActiveWorkbook.Sheets(3)).Name="temp_sheet" + str(i)
        temp_sheet = wb.ActiveSheet
        cht = wb.ActiveSheet.ChartObjects().Add(0,0,800,600)
        cht.Chart.Export("chart" + str(i) + ".png")
        i = i+1
excel.ActiveWorkbook.close
wb.DisplayAlerts = True

This opens my excel file, generates three .png images in my documents folder, and creates three new worksheets for the images, but the images are all blank.I am not sure what I can do to get the chart objects in my excel file to correctly copy to these newly created images. Any help I could get on this would be greatly appreciated as there seems to be no in depth documentation on pywin/win32com anywhere.

I've been searching the internet like mad and trying to get this to work for a day or two now... It's hard to get something to work when you don't know all of the methods available, or even what some of the methods do.

(Yes, I have read all the "read me" files that came with the library and read what they offered on their website as well.)


Solution

  • I already figured out what to do but I suppose I'll post it for future users.

    for index in range(1, count + 1):
        currentChart = wbSheet.ChartObjects(index)
        currentChart.Copy
        currentChart.Chart.Export("chart" + str(index) + ".png")
    

    I used a count to do a for loop, this way you dynamically read the amount of chart objects in an excel file.

    Also, the reason I started the range at 1 is because VB in excel starts index of objects at 1, not zero.