Download pictures from target cells in xlsx based on openpyxl

How to extract the picture of target cell location from xlsx

I. Introduction

You need to use this when doing some projects. How to say it later, ask chatGPT to answer based on the defense, and looking online is also a pile of shit. why not write it yourself

Second, the specific procedure is as follows

Change xlsx_file, sheet_name, save_path, (8,i) to what you want, you can

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)

Guess you like

Origin blog.csdn.net/qq_51116518/article/details/131048949