Search code examples
pythonwindowsexcelwinapiwin32com

Export Charts from Excel as images using Python


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.

import win32com.client as win32
excel = win32.gencache.EnsureDispatch("Excel.Application")
wb = excel.Workbooks.Open("<WORKSHEET NAME>")
r = wb.Sheets("<SHEET NAME>").Range("A1:J50") 
# Here A1:J50 is the area over which cart is
r.CopyPicture()

This is where I am stuck. I need to copy the selected range to a file now. Any help or pointers towards the doc can help me a lot.

I have modelled the above code based on the following VBA script:

Sub Export_Range_Images()
    ' =========================================
    ' Code to save selected Excel Range as Image
    ' =========================================
    Dim oRange As Range
    Dim oCht As Chart
    Dim oImg As Picture

    Set oRange = Range("A1:B2")
    Set oCht = Charts.Add
    oRange.CopyPicture xlScreen, xlPicture
    oCht.Paste
    oCht.Export FileName:="C:\temp\SavedRange.jpg", Filtername:="JPG"
End Sub

Code Snippet from : http://vbadud.blogspot.com/2010/06/how-to-save-excel-range-as-image-using.html


Solution

  • 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()