Export Charts from Excel as images using Python

前端 未结 5 629
灰色年华
灰色年华 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:54

    For me this worked well:

    from win32com.client import Dispatch
    
    app = Dispatch("Excel.Application")
    workbook_file_name = 'Programmes.xlsx'
    workbook = app.Workbooks.Open(Filename=workbook_file_name)
    
    # WARNING: The following line will cause the script to discard any unsaved changes in your workbook
    app.DisplayAlerts = False
    
    i = 1
    for sheet in workbook.Worksheets:
        for chartObject in sheet.ChartObjects():
            # print(sheet.Name + ':' + chartObject.Name)
            chartObject.Chart.Export("chart" + str(i) + ".png")
            i += 1
    
    workbook.Close(SaveChanges=False, Filename=workbook_file_name)
    

    Or this:

    from win32com.client import Dispatch
    
    app = Dispatch("Excel.Application")
    workbook_file_name = 'Programmes.xlsx'
    workbook = app.Workbooks.Open(Filename=workbook_file_name)
    app.DisplayAlerts = False
    try:
        workbook.SaveAs(Filename="ExcelCharts.htm", FileFormat=44)  # 44 = html file format
    except Exception as ex:
        print(ex)
    finally:
        workbook.Close(SaveChanges=False, Filename=workbook_file_name)
    

提交回复
热议问题