我正在尝试使用python读取Excel,Excel有两列名称为Product_Name,第二列为LOGO。顾名思义,产品名称包含产品名称,如Fish,笔记本电脑,而第二列包含该产品名称的徽标。我正在尝试从LOGO列中保存图像,图像名称为Product Name。下面的代码工作正常,但是Product Name并且保存的图片不匹配
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()
答案 0 :(得分:0)
以下脚本从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
所以我最后有以下图像: