简体   繁体   中英

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

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

I know this is an old question but it helped to put me on the right track so I came back to share my finished script that finds all charts in a worksheet and exports them as .png. The above script can work but since it just copies a range within the worksheet, you are depending on the graphs being in exactly that spot.

    import win32com.client as win32
    from win32com.client import Dispatch
    import os

    xlApp = Dispatch('Excel.Application')

    workbook = xlApp.Workbooks.Open("Book1.xls")
    xlApp.Sheets("Sheet1").Select()

    xlSheet1 = xlApp.Sheets(1)

    #WARNING: The following line will cause the script to discard any unsaved changes in your workbook
    #Ensure to save any work before running script
    xlApp.DisplayAlerts = False

    i = 0
    for chart in xlSheet1.ChartObjects():
        print chart.Name

        chart.CopyPicture()
        #Create new temporary sheet
        xlApp.ActiveWorkbook.Sheets.Add(After=xlApp.ActiveWorkbook.Sheets(3)).Name="temp_sheet" + str(i)
        temp_sheet = xlApp.ActiveSheet

        #Add chart object to new sheet.
        cht = xlApp.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

    xlApp.ActiveWorkbook.Close()
    #Restore default behaviour
    xlApp.DisplayAlerts = True

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)

Nowadays I would recommend excel2img library, served me well. Make sure you have it installed (pip install excel2img)

import excel2img

excel2img.export_img("test.xlsx", "test.gif", "Sheet1", "MyNamedRange")

If you don't need gridlines - just hide it on excel.

git rep: excel2img to learn more.

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  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM