Export Charts from Excel as images using Python

前端 未结 5 626
灰色年华
灰色年华 2020-12-01 10:20

I have been trying to export the charts from Excel as an image file (JPG or ING) in Python. I am looking at the WIn32com. Here is what I have till now.

impor         


        
5条回答
  •  自闭症患者
    2020-12-01 10:33

    I tried with below command, but nothing got updated in excel. File being open as read only? what might be issue with code.

    import win32com.client as win32
    from win32com.client import Dispatch
    import os
    xlApp = Dispatch('Excel.Application')
    workbook = xlApp.Workbooks.Open(r'C:\Users\eshsubh\Documents\EKN\DL MS1.xls')
    xlApp.Sheets("Sheet2").Select()
    xlSheet1 = xlApp.Sheets(1)
    xlApp.DisplayAlerts = False
    i = 0
    for chart in xlSheet1.ChartObjects():
     print (chart.Name)
     chart.CopyPicture()
     #Create new temporary sheet
    xlSheet1.ActiveWorkbook.Sheets.Add(After=xlSheet1.ActiveWorkbook.Sheets(3)).Name="temp_sheet" + str(i)
    xlSheet1 = sheet_ranges.ActiveSheet
    #Add chart object to new sheet.
    cht = xlSheet1.ActiveSheet.ChartObjects().Add(0,0,800, 600)
    #Paste copied chart into new object
    cht.Chart.Paste()
    #Export image
    cht.Chart.Export("chart" + str(i) + ".png")
    #This line is not entirely neccessary since script currently exits without saving
    temp_sheet.Delete()
    i = i+1  
    

提交回复
热议问题