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

如何用Python从Excel单个单元格中提取多张图片?

提取Excel单个单元格内的多张图片

你遇到的问题是因为openpyxl_image_loader的get()方法默认只返回匹配目标单元格的第一张图片。要提取单个单元格内的所有图片,需要直接通过openpyxl操作工作表的图片集合,根据图片的锚点位置判断归属。

解决方案代码

import openpyxl
from openpyxl.drawing.image import Image as OpenpyxlImage

# 加载目标Excel文件
workbook = openpyxl.load_workbook('file.xlsx')
sheet = workbook['Лист1']

# 指定要提取图片的单元格
target_cell = 'C7'
cell = sheet[target_cell]
# 转换为openpyxl内部使用的0-based索引
target_row = cell.row - 1
target_col = cell.column - 1

# 收集目标单元格内的所有图片
cell_images = []
for drawing in sheet._images:
    # 检查图片是否锚定在目标单元格(处理单单元格锚点的常见情况)
    if hasattr(drawing.anchor, 'from'):
        anchor = drawing.anchor.from
        if anchor.row == target_row and anchor.col == target_col:
            # 将openpyxl的Drawing对象转换为PIL Image
            pil_image = OpenpyxlImage(drawing._data()).image
            cell_images.append(pil_image)

# 预览所有提取到的图片
for index, img in enumerate(cell_images, 1):
    print(f"第{index}张图片")
    img.show()

# 保存图片到本地(可选)
for index, img in enumerate(cell_images, 1):
    img.save(f"{target_cell}_image_{index}.png")

代码说明

  1. 直接操作工作表图片集合:sheet._images包含了工作表内的所有图片对象,绕过openpyxl_image_loader的限制。
  2. 锚点判断归属:每张图片都有anchor属性,记录了它附着的单元格位置。通过对比锚点的行、列索引(0-based)和目标单元格的索引,筛选出属于目标单元格的图片。
  3. 图片格式转换:将openpyxl的Drawing对象转换为PIL Image,方便预览或保存。

扩展说明

如果图片是跨单元格的(使用TwoCellAnchor),可以扩展判断逻辑,检查目标单元格是否在图片的锚点覆盖范围内:

# 处理跨单元格的图片锚点
if hasattr(drawing.anchor, 'from') and hasattr(drawing.anchor, 'to'):
    anchor_from = drawing.anchor.from
    anchor_to = drawing.anchor.to
    # 判断目标单元格是否在图片覆盖的范围内
    if (anchor_from.row <= target_row <= anchor_to.row 
        and anchor_from.col <= target_col <= anchor_to.col):
        pil_image = OpenpyxlImage(drawing._data()).image
        cell_images.append(pil_image)

内容的提问来源于stack exchange,提问作者Светлана Фарбовская

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 09:51:09