You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用openpyxl的image_loader读取Excel同一单元格内的多张图片

openpyxl读取同一单元格多张图片的实现方案

openpyxl内置的image_loader默认仅会返回单个单元格匹配到的第一张图片,要获取同一单元格内的多张图片,直接遍历工作表存储所有图片的底层属性_images,按图片锚定的单元格位置筛选即可。

完整实现代码

from openpyxl import load_workbook

# 1. 加载目标Excel文件
wb = load_workbook("测试文件.xlsx")
# 选中目标工作表
ws = wb["Sheet1"]

# 2. 定义要提取图片的目标单元格(示例为A2单元格,行号列号均为Excel展示的1起始编号)
target_cell_row = 2
target_cell_col = 1

# 转换为openpyxl内部使用的0起始索引
target_row_idx = target_cell_row - 1
target_col_idx = target_cell_col - 1

# 3. 遍历所有工作表图片,筛选锚定在目标单元格的图片
target_imgs = []
for img in ws._images:
    # 获取图片左上角锚定的单元格位置
    img_anchor_row = img.anchor._from.row
    img_anchor_col = img.anchor._from.col
    if img_anchor_row == target_row_idx and img_anchor_col == target_col_idx:
        target_imgs.append(img)

print(f"当前单元格共找到{len(target_imgs)}张图片")

# 4. 将筛选到的图片保存到本地
for index, img in enumerate(target_imgs):
    # 适配原始图片的格式(png/jpg等)
    img_suffix = img.format.lower()
    save_path = f"目标单元格第{index+1}张图片.{img_suffix}"
    with open(save_path, "wb") as f:
        f.write(img.ref.getvalue())

注意事项

  • 锚点匹配逻辑说明:上述代码是按图片左上角锚定的单元格匹配,若需要筛选完全包含在目标单元格内的图片,可额外增加img.anchor.to.row == target_row_idx和img.anchor.to.col == target_col_idx的判断条件。
  • 属性兼容性说明:ws._images属于openpyxl的非公开属性,目前3.0及以上所有稳定版本均支持该调用方式,后续版本如有变动可通过官方文档查询对应替代属性。
  • 该方案仅适用于xlsx格式文件,若处理xls格式旧版Excel文件,需更换为xlrd等其他库实现。

内容的提问来源于stack exchange,提问作者curious_katey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 09:45:05