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

如何用Python删除或更新Excel中指定单元格内的图片?

解决Python操作Excel时删除指定单元格内图片的问题

方法一:使用openpyxl

openpyxl是处理xlsx格式的常用库,要定位并删除指定单元格(如C6)内的图片,可通过判断图片的锚点位置或覆盖区域实现:

  1. 加载目标工作簿和工作表
  2. 遍历所有图片,检查其是否与目标单元格关联
  3. 删除匹配图片后插入新图片
from openpyxl import load_workbook
from openpyxl.drawing.image import Image

# 加载工作簿和工作表
wb = load_workbook("your_file.xlsx")
ws = wb["Sheet1"]  # 替换为你的工作表名

# 目标单元格:C6(openpyxl中列从0开始,行从0开始,所以C对应2,6对应5)
target_col = 2
target_row = 5

# 遍历并删除锚点在目标单元格的图片
images_to_delete = []
for img in ws._images:
    col_idx = img.anchor._from.col
    row_idx = img.anchor._from.row
    if col_idx == target_col and row_idx == target_row:
        images_to_delete.append(img)

for img in images_to_delete:
    ws._images.remove(img)

# 插入新图片到C6
new_img = Image("new_image.png")
new_img.anchor = "C6"
ws.add_image(new_img)

# 保存工作簿
wb.save("updated_file.xlsx")

若图片是覆盖目标单元格而非锚点在左上角,可调整判断逻辑,检查图片边界是否包含目标单元格范围。

方法二:使用xlwings

xlwings贴近Excel原生操作,定位指定单元格的图片更直观:

import xlwings as xw

# 后台打开Excel文件
app = xw.App(visible=False)
wb = app.books.open("your_file.xlsx")
ws = wb.sheets["Sheet1"]

# 目标单元格C6
target_cell = ws.range("C6")

# 删除该单元格关联的所有图片
for shape in ws.shapes:
    # 判断形状位置是否与目标单元格重合
    if shape.topleft_cell.address == target_cell.address or \
       shape.bottomright_cell.address == target_cell.address:
        shape.delete()

# 插入新图片到C6位置
ws.pictures.add("new_image.png", left=target_cell.left, top=target_cell.top)

# 保存并关闭文件
wb.save("updated_file.xlsx")
wb.close()
app.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:42:07