首页 > 解决方案 > 使用python从Excel文件中提取图像

问题描述

我有一个 100 行的 Excel 表。每个都有不同的信息,包括一个 id 和一个包含照片的单元格。

我使用 pandas 将数据加载到字典中:

import pandas as pd

df = pd.read_excel('myfile.xlsx')

data = []

for index,row in df.iterrows():
    data.append({
        'id':row['id'],
        'field2':row['field2'],
        'field3':row['field3']
    })

对于图像列,我想提取每个图像,用行的 id 命名(image_row['id'].jpg)并将其放入文件夹中。然后,我想存储图像的路径,如下所示:

for index,row in df.iterrows():
        data.append({
            'id':row['id'],
            'field2':row['field2'],
            'field3':row['field3'],
            'image':'path/image_'+row['id']+'.jpg'
        })

我正在寻找一种方法来做到这一点,或者如果更好的话。你有什么主意吗 ?

我在 Linux 上,所以我不能将此方法与 pywin32 一起使用。

非常感谢

- 编辑

你可以在这里找到我使用的工作表示例

标签: pythonexcelimage

解决方案


我找到了使用openpyxlopenpyxl-image-loader模块的解决方案

# installing the modules
pip3 install openpyxl
pip3 install openpyxl-image-loader

然后,在脚本中:

#Importing the modules
import openpyxl
from openpyxl_image_loader import SheetImageLoader

#loading the Excel File and the sheet
pxl_doc = openpyxl.load_workbook('myfile.xlsx')
sheet = pxl_doc['Sheet_name']

#calling the image_loader
image_loader = SheetImageLoader(sheet)

#get the image (put the cell you need instead of 'A1')
image = image_loader.get('A1')

#showing the image
image.show()

#saving the image
image.save('my_path/image_name.jpg')

最后,我可以将路径和图像名称存储在字典中的每一行的循环中


推荐阅读