Python Export Excel Sheet Range as Image

13,723

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

Solution 2

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

Share:
13,723
David Yang
Author by

David Yang

Updated on July 10, 2022

Comments

  • David Yang
    David Yang almost 2 years

    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?

  • igorkf
    igorkf over 4 years
    That's gonna be so useful to me! Thanks
  • Jim.W
    Jim.W over 4 years
    I am getting a AttributeError: xlBitmap error when adding the format = win32c.sxlbitmap
  • Python Bang
    Python Bang about 4 years
    This dont support for microsoft excel 2016. any alternatives ?
  • Admin
    Admin over 2 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
  • ambigus9
    ambigus9 over 2 years
    @PythonBang did you find any solution?