Cup*_*ain 3 python excel image
我有一个 100 行的 Excel 工作表。每个都有各种信息,包括一个 id 和一个包含照片的单元格。
我使用熊猫将数据加载到字典中:
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']
})
Run Code Online (Sandbox Code Playgroud)
对于图像列,我想提取每个图像,使用行的 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'
})
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种方法来做到这一点,或者另一种更好的方法。你有什么主意吗 ?
我在 Linux 上,所以我不能在 pywin32 上使用这种方法。
非常感谢
- 编辑
您可以在此处找到我使用的工作表示例
我找到了一个使用openpyxl和openpyxl-image-loader模块的解决方案
# installing the modules
pip3 install openpyxl
pip3 install openpyxl-image-loader
Run Code Online (Sandbox Code Playgroud)
然后,在脚本中:
#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')
Run Code Online (Sandbox Code Playgroud)
最后,我可以将字典中的路径和图像名称存储在每行的循环中
小智 6
def extract_images_from_excel(path, dir_extract=None):
"""extracts images from excel and names then with enumerated filename
Args:
path: pathlib.Path, excel filepath
dir_extract: pathlib.Path, default=None, defaults to same dir as excel file
Returns:
new_paths: list[pathlib.Path], list of paths to the extracted images
"""
if type(path) is str:
path = pathlib.Path(path)
if dir_extract is None:
dir_extract = path.parent
if path.suffix != '.xlsx':
raise ValueError('path must be an xlsx file')
name = path.name.replace(''.join(path.suffixes), '').replace(' ', '') # name of excel file without suffixes
temp_file = pathlib.Path(source_file).parent / 'temp.xlsx' # temp xlsx
temp_zip = temp_file.with_suffix('.zip') # temp zip
shutil.copyfile(source_file, temp_file)
temp_file.rename(str(temp_zip))
extract_dir = temp_file.parent / 'temp'
extract_dir.mkdir(exist_ok=True)
shutil.unpack_archive(temp_zip, extract_dir) # unzip xlsx zip file
paths_img = sorted((extract_dir / 'xl' / 'media').glob('*.png')) # find images
move_paths = {path: destination_dir / (name + f'-{str(n)}.png') for n, path in enumerate(paths_img)} # create move path dict
new_paths = [shutil.move(old, new) for old, new in move_paths.items()] # move / rename image files
shutil.rmtree(extract_dir) # delete temp folder
temp_zip.unlink() # delete temp file
return new_paths
Run Code Online (Sandbox Code Playgroud)
上面的 ^ 执行以下操作:
不需要第 3 方软件包,也不需要 Windows 来运行