基于openpyxl 从xlsx中的目标单元格中下载图片

如何从xlsx中提取目标单元格位置的图片

一,前言

做一些项目的时候需要用到这一点,后来怎么说,问chatGPT回答依托答辩,网上找也是一坨大便。不如自己写

二,具体程序如下

改改xlsx_file,sheet_name,save_path, (8,i)为你要的,即可

from openpyxl import load_workbook
from PIL import Image

def download_image_from_cell(filename, sheetname, target_cell, save_path):
    wb = load_workbook(filename)
    sheet = wb[sheetname]

    for image1 in sheet._images:
        image_anchor = image1.anchor
        image= image_anchor._from


        col, colOff, row, rowOff=image.col,image.colOff,image.row,image.rowOff
       # print(col,colOff,row,rowOff)
        #print(image_anchor)
        # 检查图像的锚定位置是否与目标单元格匹配
        if (col,row) == target_cell:
            # 获取图像的数据

            # 将图像数据保存到文件
            img = Image.open(image1.ref).convert("RGB")
           # img = np.array(img)

            img.save(save_path)


            print(f"已下载图像: {save_path}")

    wb.close()

# 指定要读取的 xlsx 文件路径、工作表、目标单元格和保存路径
xlsx_file = '/Users/yanghao31/Desktop/test/iconsFInal/NewIcos13.xlsx'
sheet_name = 'Sheet'
target_cell = 'F2'
for i in range(1,8):
    save_path = 'path_to_save_image{}.png'.format(str(i))

    # 调用函数读取特定单元格中的图像并下载
    download_image_from_cell(xlsx_file, sheet_name, (8,i), save_path)

猜你喜欢

转载自blog.csdn.net/qq_51116518/article/details/131048949