Export Charts from Excel as images using Python

I had to look at some VBA examples to get this working. Although I hate answering my own questions, I am leaving this here for people who might need it.

    import win32com.client as win32
    wb = excel.Workbooks.Open(excel_file)
    selection = "A1:J30" 
    xl_range = wb.Sheets(<sheet_name>).Range(selection)
    excel.ActiveWorkbook.Sheets.Add(                  After=excel.ActiveWorkbook.Sheets(3)).Name="image_sheet"
    cht = excel.ActiveSheet.ChartObjects().Add(0,0,
                                            xl_range.Width, xl_range.Height)
    xl_range.CopyPicture()
    # add the chart to new sheet
    cht.Chart.Paste()
    # Export the sheet with the chart to a new file
    cht.Chart.Export(<image_filename>)
    # Delete the sheet
    cht.Delete()
    excel.ActiveSheet.Delete()
    # Close the book
    excel.ActiveWorkbook.Close()

Leave a Comment