Python从剪贴板保存xlPicture

Python从剪贴板保存xlPicture

问题描述:

当前,我有一个xlPicture(通过win32com)保存在剪贴板中(通过win32com):

Currently I have an xlPicture saved in my clipboard from the call (via win32com):

ws.Range(ws.Cells(1,1),ws.Cells(8+rows,total_length)).CopyPicture() #Copies xlPicture to clipboard

现在我想将剪贴板中的图像保存到文件中,所以我尝试使用PIL:

Now I want to save the image in my clipboard to a file, so I tried using PIL:

    from PIL import ImageGrab
    img = ImageGrab.grabclipboard()
    img.save(os.path.join(r'C:\Windows\Temp\WS_Template_Images','test.png'),'PNG')

但是ImageGrab.grabclipboard()返回None,我假设xlPicture在某种程度上不是该呼叫的兼容类型.我可以使用ImageGrab进行任何更改,还是可以完全保存xlPicture的替代解决方案?谢谢!

But ImageGrab.grabclipboard() returns None, I assume xlPicture is somehow not a compatible type for the call. Is there anything I can change to use ImageGrab or is there an alternate solution completely to saving an xlPicture? Thanks!

事实证明,我可以通过以下简单的方法来实现:

It Turns out I can achieve this with the simple work around of :

ws.Range(ws.Cells(1,1),ws.Cells(8+rows,total_length)).CopyPicture()    
wb = excel.Workbooks.Add()
ws = wb.ActiveSheet
ws.Paste()
ws.Shapes('Picture 1').Copy()
img = ImageGrab.grabclipboard()
imgFile = os.path.join(r'C:\Windows\Temp\WS_Template_Images','test.png')
img.save(imgFile)

将图像粘贴到新工作簿中,然后重新复制并保存作品,因为这样可以取消单元格数据的链接,因此它被认为是ImageGrab现在可以获取的图像.

Pasting the image in a new workbook and then recopying and saving works, because this way the cell data is unlinked and it is considered an Image which ImageGrab can now get.