如何将Excel中的图像保存到文件夹

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

我有一个包含图像的 Excel 文件,我想使用 python 将它们保存在一个文件夹中。

我过去曾在java中完成过此操作,迭代工作表中的图像并使用aspose.cells将它们保存为字节数组。现在,由于代码输出中的一些问题,我需要通过 python 执行相同的操作。我可以这样做吗?如果是,我该怎么做?

这是我正在使用的python(从java转换而来)代码-

import openpyxl
wb = load_workbook("myfile.xlsx")
sheet = wb["sheet1"]
 header_name = ""
 pic_name = ""

 if sheet is not None:
    pics = sheet._images
    for pic in pics:
        header_name = ""
        pic_bytes = bytearray(pic)

        if pic.anchor.row - 2 >= 0:
           header_name = sheet.cell(row=pic.anchor.row - 2, column=pic.anchor.col_idx -1).value.strip()
           pic_name = header_name + ".png"
           Mainclass.PicBytes_map_sheet[pic_name] = pic_bytes 
python excel openpyxl
1个回答
0
投票

您可以使用 SheetImageLoader ,这是一个有人使用 Openpyxl 编写的小实用程序来获取工作表中图像的位置。
然后将它们保存到文件中即可。

import os.path
import openpyxl
from openpyxl_image_loader import SheetImageLoader


# Load workbook
wb = openpyxl.load_workbook('saved.xlsx')
ws = wb['Sheet2']

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

# Set path for saved images
images_path = 'images'

### Loop to find the images location and copy to the new work book/sheet
for image_loc in image_loader._images:
    print(f"Image located at: {image_loc}")

    img = image_loader.get(image_loc)
    print(f"Default Image Size: height: {img.height}, width: {img.width}")

    image_file = os.path.join(images_path, f'image_{image_loc}.png')
    img.save(image_file, format='PNG')
© www.soinside.com 2019 - 2024. All rights reserved.