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?
Unfortunately, Excel doesn't let you export spreadsheets into images. But you can turn them into images by jumping through a few hoops. First, try taking a screenshot of your spreadsheet. Or simply highlight the data you want to send, select Home > Copy > Copy As Picture, and paste the data into a graphics editor.
How to save/export table as image? In Excel, select the table, and copy it with pressing Ctrl + C keys. Launch the Paint program, paste the table with pressing Ctrl + V keys, and then click Home > Crop. Click File > Save.
Alternatively, on the Home tab, in the Clipboard group, click the little arrow next to Copy, and then click Copy as Picture… Open Microsoft Paint or any other graphics editor. Press Ctrl + V to paste the copied data. Save the newly created file as GPEG, GIF or PNG image.
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.
To clarify those comments of Florent B. and David Yang
Add optional parameter Format
into .CopyPicture()
will make ImageGrab.getclipboard()
work as expected.
The following code will bews.Range(ws.Cells(1,1),ws.Cells(66,16)).CopyPicture(Format = 2)
Number 2
is xlBitmap, refer to https://docs.microsoft.com/en-us/office/vba/api/excel.range.copypicture
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With