我需要一种方法将图像从一个Excel文件复制到Python中的新文件

问题描述 投票:0回答:1

我尝试使用 openpyxl 和 SheetImageLoader

这是我能做的最好的事情,脚本复制图像,但仅当文件中有一张纸并且不保留图像大小时才有效

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')
python excel openpyxl
1个回答
0
投票

openpyxl
库提供了一种直接访问 Excel 文件中图像的方法,无需额外的图像加载器。这是解决这些问题的代码的更新版本:

import openpyxl
from openpyxl.drawing.image import Image

# 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

# Copy values and styles from source sheet to destination sheet
for row in src_sheet.iter_rows():
    for cell in row:
        dest_cell = dest_sheet[cell.coordinate]
        dest_cell.value = cell.value
        if cell._image:
            img = cell._image
            img_copy = Image(img.image)
            dest_cell._image = img_copy

# Save destination workbook
dest_wb.save('C:\\miso\\testy\\new_excel_file.xlsx')
© www.soinside.com 2019 - 2024. All rights reserved.