Search code examples
pythonimagecopyopenpyxl

Python openpyxl _images get data?


My python version is 3.11 openpyxl 3.1.2

path = r"D:\input"
wb = op.load_workbook(path + "/test.xlsx")
ws = wb.active 

data1 = ws["B2"].value
img_obj = ws._images[0]

img_data = img_obj.image # error

I'm trying to get image data but I'm getting this error;

AttributeError: 'Image' object has no attribute 'image'

So I tried changing it to the property of img_obj.img_data, but the result was the same.

img_data = img_obj.image_data # error

How can I access my image data? I'd like to insert image into my cell like this :

ws.add_image(img_obj, "D6")

There is no problem with files outside the Excel file,
and this problem occurs when I try to copy the image inside the Excel.


Solution

  • The following code should do what it looks like you want.
    Basically copy and existing image in the sheet to another location

    The only trouble is I tried it with the latest openpyxl version 3.1.2 and found that image_loader.get(image_loc) causes an issue with the workbook and if don't reload the workbook and sheet again I get an error and corrupted workbook. When they are reloaded as shown the file saves correctly.
    The code works on the original version I wrote this for which is 3.0.9 without having to reload the workbook/worksheet so maybe its an bug with the latest release.

    import openpyxl as op
    from openpyxl.drawing.image import Image
    from openpyxl_image_loader import SheetImageLoader
    
    
    path = r"D:\input"
    wb = op.load_workbook(path + "/test.xlsx")
    ws = wb.active
    
    image_loc = 'A2' # Location of the original image in the sheet
    image_loader = SheetImageLoader(ws)
    
    ### This loop can be used to find the image location if not known
    # for image_loc in image_loader._images:
    #     print(image_loc)
    #     image_list_loc = image_loc
    
    ### load image from image location
    ### When this line is run on openpyxl 3.1.2 need to reload the workbook/sheet
    image = Image(image_loader.get(image_loc))
    
    ### Reload the workbook and sheet
    wb = op.load_workbook("test.xlsx")
    ws = wb.active
    
    ### Add the image to new location
    ws.add_image(image, 'D6')
    
    ### Save workbook
    wb.save('test.xlsx')
    

    Image at cell "A2" copied to cell "D6"
    Example