Python Export Excel Sheet Range as Image

Viewed 17581

So it seems there's something weird going on with PIL ImageGrab.grabclipboard()

import win32com.client
from PIL import ImageGrab

o = win32com.client.Dispatch('Excel.Application')
o.visible = False

wb = o.Workbooks.Open(path)
ws = wb.Worksheets['Global Dash']

ws.Range(ws.Cells(1,1),ws.Cells(66,16)).CopyPicture()  
img = ImageGrab.grabclipboard()
imgFile = os.path.join(path_to_img,'test.jpg')
img.save(imgFile)

When I run this, I notice that if I ctrl-V , the image is actually correctly saved on the clipboard, but my img variable returns None, meaning ImageGrab.grabclipboard() is somehow not working. Any ideas?

6 Answers

Here I have a solution which might help you.

import excel2img
excel2img.export_img("example.xlsx/example.csv","image.png/image.bmp","sheet!B2:H22")

This is working perfectly for me.

I just replaced ws.Range(ws.Cells(1,1),ws.Cells(66,16)).CopyPicture() by ws.Range(ws.Cells(1,1),ws.Cells(66,16)).Copy() and it worked perfectly.

So this is the entire code.

import win32com.client
from PIL import ImageGrab

o = win32com.client.Dispatch('Excel.Application')
o.visible = False

wb = o.Workbooks.Open(path)
ws = wb.Worksheets['Global Dash']

ws.Range(ws.Cells(1,1),ws.Cells(66,16)).Copy()  
img = ImageGrab.grabclipboard()
imgFile = os.path.join(path_to_img,'test.jpg')
img.save(imgFile)

I just tried the method posted in the comments under the question and it actually works!
Pay attention to use win32com.client.constants to get the xlBitmap.
In addition, my environment is Python 3.6 and I haven't tried it again in Python 2.7.

win32c = win32com.client.constants
ws.Range(ws.Cells(1,1),ws.Cells(66,16)).CopyPicture(Format= win32c.xlBitmap)

img = ImageGrab.grabclipboard()
imgFile = os.path.join(path_to_img,'test.jpg')
img.save(imgFile)

This solution worked for me. Try to start Excel with:

o = win32com.client.gencache.EnsureDispatch("Excel.Application")

Then use win32com.client.constants to get the xlBitmap

wb = o.Workbooks.Open(workbook_file_name)
ws = wb.Worksheets("Vs. Disk or Retrofit Chart View")
ws.Range(ws.Cells(22,1),ws.Cells(62,8)).CopyPicture(Format= win32com.client.constants.xlBitmap)  
img = ImageGrab.grabclipboard()
imgFile = os.path.join(os.getcwd(),'test.jpg')
img.save(imgFile)

The best way to do it is:

import win32com.client
from PIL import ImageGrab

wb_file_name = 'Input.xlsx'
outputPNGImage = 'Output.png'

xls_file = win32com.client.gencache.EnsureDispatch("Excel.Application")

wb = xls_file.Workbooks.Open(Filename=wb_file_name)
xls_file.DisplayAlerts = False 
ws = wb.Worksheets("Desired_Tab")
ws.Range(ws.Cells(1,1),ws.Cells(15,3)).CopyPicture(Format= win32com.client.constants.xlBitmap)  # example from cell (1,1) to cell (15,3)
img = ImageGrab.grabclipboard()
img.save(outputPNGImage)
wb.Close(SaveChanges=False, Filename=wb_file_name)
Related