python - 打开多个 Excel 文件,打开每个文件的每个工作表,然后保存图像

标签 python excel python-3.x xlsx

我有多个包含图像的 Excel 文件,这些图像位于不同的 Excel 工作表上。我的目标是将图像保存到我的计算机上。这些图像稍后将用于人脸识别。

我构建了一些代码来打开 Excel 文件并抓取图像。然而,它只取一张纸而不是所有纸。

import face_recognition
import pandas as pd
import win32com.client as win32
from PIL import ImageGrab
import os

#Read working directory
print(os.getcwd()) #get current working directory
os.chdir("E:/DATA/Master data") #set working directory
print(os.getcwd())#check updated working directory

#Reading xlsx file in a folder
path1="E:/DATA/Master data"
files= os.listdir(path1)
print(files)
listlength = len(files)

#Extracting data from each xlsx file
for f in files:
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    count=0
while (count<listlength):
    a = files.pop(count)
    path_name = path1 + "/" + a
    workbook = excel.Workbooks.Open(path_name)
    wb_folder = workbook.Path
    wb_name = workbook.Name
    wb_path = os.path.join(wb_folder, wb_name)
    for sheet in workbook.Worksheets:
        for i, shape in enumerate(sheet.Shapes):
            if shape.Name.startswith('Picture'):
                shape.Copy()
                image = ImageGrab.grabclipboard()
                image.save('{}.jpg'.format(i+1), 'jpeg')

我希望从多个 Excel 文件的每个工作表中获取所有图像。

最佳答案

每个工作表的变量 i 都会被重置,因此您的文件名是相同的,因此文件将被覆盖。添加第二个变量,该变量会针对每个工作表递增,因此文件名也包含该变量。

这经过测试可以正常工作,我添加了 excel.Visible,以便您可以看到弹出的工作表:) 还可以进行记录,以便您可以看到发生了什么。我没有使用全局计数变量,而是将工作簿名称连接到工作表名称,然后使用每个工作表图像中的“n”变量。

import win32com.client as win32
from PIL import ImageGrab
import os

def ensureDirExists(filePath):
    if not os.path.exists(filePath):
        os.makedirs(filePath)

def absoluteListDir(directory):
   for dirpath,_,filenames in os.walk(directory):
       for f in filenames:
           yield os.path.abspath(os.path.join(dirpath, f))

dataDirectory = "data"
outputDirectory = "images"

ensureDirExists(dataDirectory)
ensureDirExists(outputDirectory)

excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = True

files = absoluteListDir(dataDirectory)

for file in files:
    print("=" * 20)
    print("Opening Workbook: ", file)
    workbook = excel.Workbooks.Open(file)

    for sheet in workbook.Sheets:
        print("Scraping Sheet: ", sheet.Name)
        for n, shape in enumerate(sheet.Shapes):
            if shape.Name.startswith("Picture"):
                shape.Copy()
                image = ImageGrab.grabclipboard()
                outputFile = "{}/{}_{}_{}.jpg".format(outputDirectory, workbook.Name, sheet.Name, n)
                print("Saving Image File: ", outputFile)
                image.save(outputFile, "jpeg")

    print("Closing Workbook")
    workbook.Close(True)

关于python - 打开多个 Excel 文件,打开每个文件的每个工作表,然后保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56900714/

相关文章:

python - Python 中的 MATLAB spconvert

Python - 在内存中查找当前对象

python - 在不保存的情况下在 Jupyter Notebook 中打开 base64 字符串图像

python - Azure Functions 如何在脚本完成之前返回 HttpResponse 或显示消息

java - 将电子表格转换为 Javabean

excel - 将行与上面的行相乘并获得平均值

excel - 如果放入列中的值不是唯一的,则获取消息

python-3.x - 在 __post_init__ 中设置可选数据类参数时如何避免检查 None

python - 如何在 Python 中使用 Bokeh 查看 Holoviews 的选项

python - 将 matplotlib 保存为最终给定大小(包括标题)