I have several Excel charts which I would like to export as images with Python. Every chart is in a separate Excel file with only 1 sheet. This script works for almost all my charts:
import win32com.client as win32
from win32com.client import Dispatch
xl = Dispatch('Excel.Application')
xl.Visible = True
wb = xl.Workbooks.Open("C:\\test.xlsx")
xl.DisplayAlerts = False
chart = wb.Worksheets(1).ChartObjects(1)
chart.CopyPicture()
#Create new temporary sheet (after first sheet)
xl.ActiveWorkbook.Sheets.Add(After=xl.ActiveWorkbook.Sheets(1)).Name="temp_sheet"
temp_sheet = xl.ActiveSheet
#Add chart object to new sheet.
cht = xl.ActiveSheet.ChartObjects().Add(0,0,chart.Width, chart.Height)
#Paste copied chart into new object
cht.Activate() # dit is bij de topsheets nodig, anders plakt die een wit vlak... (bij trends en staafjes hoeft het niet)
cht.Chart.Paste()
#Export image
cht.Chart.Export("C:\\test.png")
temp_sheet.Delete()
xl.ActiveWorkbook.Close()
#Restore default behaviour
xl.DisplayAlerts = True
I have one chart however that cannot be exported... I get this error after the export function:
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147287037), None)
The chart is copied to the temporary sheet, but export fails. In some old Excel-VBA code written for exporting this chart I see this line:
ActiveSheet.PasteSpecial Format:="Bitmap", Link:=False,
DisplayAsIcon:=False
What is the Python equivalent? This:
cht.Chart.PasteSpecial(Format="Bitmap")
Is not working (AttributeError: '' object has no attribute 'PasteSpecial')
- edit -
The "clipboard comment" from Xukrao pointed me in another direction. With the help of this tutorial https://www.penwatch.net/cms/images_from_excel/ I used ImageGrab from PIL. Exporting the chart is working now! :)
import win32com.client as win32
from win32com.client import Dispatch
xl = Dispatch('Excel.Application')
xl.Visible = True
wb = xl.Workbooks.Open("C:\\test.xlsx")
xl.DisplayAlerts = False
chart = wb.Worksheets(1).ChartObjects(1)
chart.CopyPicture()
#Create new temporary sheet (after first sheet)
xl.ActiveWorkbook.Sheets.Add(After=xl.ActiveWorkbook.Sheets(1)).Name="temp_sheet"
temp_sheet = xl.ActiveSheet
xl.ActiveSheet.PasteSpecial()
# Use PIL (python imaging library) to save from Windows clipboard
# to a file
wb.Worksheets(2).Pictures(1).Copy()
image = ImageGrab.grabclipboard()
image.save('blabla.bmp','bmp')
#This line is not entirely neccessary since script currently exits without
saving
temp_sheet.Delete()
xl.ActiveWorkbook.Close()
#Restore default behaviour
xl.DisplayAlerts = True