Insert image in openpyxl

后端 未结 5 2019
不知归路
不知归路 2020-12-14 02:28

Is it possible to insert an image (jpeg, png, etc) using openpyxl?

Basically I want to place a generated image with a chart below it.

I don\'t see anything i

5条回答
  •  粉色の甜心
    2020-12-14 03:08

    Providing a full update on how to do this. This solution uses openpyxl version 2.4.5.

    I downloaded an image to my local directory, opened an existing workbook and saved with the image inserted.

    import openpyxl
    from openpyxl import load_workbook
    from openpyxl import Workbook
    from openpyxl.drawing.image import Image
    from openpyxl.utils import coordinate_from_string
    
    openpyxl_version = openpyxl.__version__
    print(openpyxl_version)  #to see what version I'm running
    
    # downloaded a .png to local directory manually from
    # "https://www.python.org/static/opengraph-icon-200x200.png"
    
    #change to the location and name of your image
    png_loc = r'c:\users\me\opengraph-icon-200x200.png'
    
    # test.xlsx already exists in my current directory 
    
    wb = load_workbook('test.xlsx')
    ws = wb.active
    my_png = openpyxl.drawing.image.Image(png_loc)
    ws.add_image(my_png, 'B3')
    wb.save('test.xlsx')
    

    Results:

提交回复
热议问题