Python win32 Excel paste chart as bitmap (PasteSpecial)?

I have several Excel charts that I would like to export as images using Python. Each chart is in a separate Excel file with only 1 sheet. This script works for almost all of my graphs:

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 that cannot be exported ... I am getting this error after the export function:

pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147287037), None)

      

The graph was copied to a temporary sheet, but the export failed. In some old Excel-VBA code written to export this chart, I see this line:

ActiveSheet.PasteSpecial Format:="Bitmap", Link:=False, 
DisplayAsIcon:=False

      

What is the Python equivalent? It:

cht.Chart.PasteSpecial(Format="Bitmap")

      

Doesn't work (AttributeError: '' object has no attribute 'PasteSpecial')

  • Edit -

The "clipboard comment" from Xukrao pointed me in a different direction. With this tutorial https://www.penwatch.net/cms/images_from_excel/ I have used ImageGrab from PIL. Chart export works 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

      

+3


source to share


1 answer


Direct Python equivalent

ActiveSheet.PasteSpecial Format:="Bitmap", Link:=False, DisplayAsIcon:=False

      



:

xl.ActiveSheet.PasteSpecial(Format="Bitmap", Link=False, DisplayAsIcon=False)

      

0


source







All Articles