Reputation: 3
I am trying to read an excel using python, Excel has two columns name as Product_Name and second is LOGO. product Name as the name suggests contains the Product Name Like Fish ,Laptop whereas Second columns contain the logo of that Product Name.I am trying to save images from the LOGO column with image name as Product Name .Below Code is working fine but Product Name and saved Images are mismatching
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()
Upvotes: 0
Views: 6360
Reputation: 8270
Following script extracts all images from Excel file and name them with "Channel name" value:
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
So I've got following images on the end:
Upvotes: 1