【问题标题】:Export Images From Excel using Python with specific name使用具有特定名称的 Python 从 Excel 导出图像
【发布时间】:2019-05-28 09:05:59
【问题描述】:

我正在尝试使用 python 读取 Excel,Excel 有两列名称作为 Product_Name,第二列是 LOGO。顾名思义,产品名称包含产品名称,如鱼,笔记本电脑,而第二列包含该产品名称的徽标。我正在尝试从 LOGO 列中保存图像,图像名称为产品名称。下面的代码工作正常,但产品名称和保存的图像不匹配

import win32com.client       # Need pywin32 from pip
from PIL import ImageGrab    # Need PIL as well
import os
excel = win32com.client.Dispatch("Excel.Application")
workbook = excel.ActiveWorkbook
wb_folder = workbook.Path
wb_name = workbook.Name
wb_path = os.path.join(wb_folder, wb_name)
print(wb_path)
print("Extracting images from %s" % wb_path)
image_no = 0
for sheet in workbook.Worksheets:
    if(sheet.Name == "Ch"):    
        for shape,r in zip(sheet.Shapes,range(4,200)):
            if shape.Name.startswith("Picture"):
                image_no += 1
                print("---- Image No. %07i ----" % image_no)
                print(r)
                imagen = sheet.Cells(r,'E').value
                filename = sheet.Cells(r,'E').value + ".jpg"
                file_path = os.path.join (wb_folder, filename)
                print("Saving as %s" % file_path)    # Debug output
                shape.Copy() # Copies from Excel to Windows clipboard
                # Use PIL (python imaging library) to save from Windows clipboard
                # to a file
                image = ImageGrab.grabclipboard()
                print(image)
                try:
                    image.save(file_path,'jpeg')
                except AttributeError:
                    F = open('error.txt','w') 
                    F.write(imagen)
                    F.close()

【问题讨论】:

标签: python python-3.x image pywin32


【解决方案1】:

以下脚本从 Excel 文件中提取所有图像并使用“通道名称”值命名它们:

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

FILE = r'C:\Users\user\Desktop\so\53994108\logo.xlsx'
CELLS = [(4, 5, 'F'), (3, 3, 'D')]

excel = win32.gencache.EnsureDispatch('Excel.Application')
workbook = excel.Workbooks.Open(FILE)
for i, worksheet in enumerate(workbook.Sheets):
    row = CELLS[i][0]
    while True:
        name = worksheet.Cells(row, CELLS[i][1]).Value
        if not name:
            break
        name = re.sub(r'\W+ *', ' ', name)
        rng = worksheet.Range('{}{}'.format(CELLS[i][2], row))
        rng.CopyPicture(1, 2)
        im = ImageGrab.grabclipboard()
        im.save('{}.jpg'.format(name))
        row += 1

所以我最后得到了以下图片:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 2022-10-06
    相关资源
    最近更新 更多