Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Export Excel Sheet Range as Image

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?

like image 569
David Yang Avatar asked Jun 30 '17 15:06

David Yang


People also ask

Can you export a Excel sheet as image?

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 do I save an Excel table as a picture in Python?

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.

How do I save an Excel spreadsheet as a PNG?

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.


2 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.

like image 130
Jagadeeswara Reddy P Avatar answered Sep 17 '22 16:09

Jagadeeswara Reddy P


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 be
ws.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

like image 38
Shuu Terumi Avatar answered Sep 21 '22 16:09

Shuu Terumi