问题
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?
回答1:
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.
回答2:
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)
来源:https://stackoverflow.com/questions/44850522/python-export-excel-sheet-range-as-image