I need a way to copy images from one excel file to a new one in python

I tried using openpyxl and SheetImageLoader

Here’s the best I could do, the script copies the images but works only if there’s one sheet in the file and doesn’t retain image size

import openpyxl
from openpyxl_image_loader import SheetImageLoader
from io import BytesIO

# Load source workbook
src_wb = openpyxl.load_workbook('C:\\miso\\testy\\new_excel_file3.xlsx')
src_sheet = src_wb.active

# Create destination workbook
dest_wb = openpyxl.Workbook()
dest_sheet = dest_wb.active

# Load images from source sheet
image_loader = SheetImageLoader(src_sheet)

# Insert images into destination sheet
for row in src_sheet:
    for cell in row:
        if image_loader.image_in(cell.coordinate):
            img = image_loader.get(cell.coordinate)
            img_stream = BytesIO()
            img.save(img_stream, format="PNG")
            img_openpyxl = openpyxl.drawing.image.Image(img_stream)
            dest_sheet.add_image(img_openpyxl, cell.coordinate)

# Save destination workbook
dest_wb.save('C:\\miso\\testy\\new_excel_file.xlsx')

Leave a Comment