Reputation: 45
I am trying to copy an image from an excel named Inputs_v3 and sheet named Inputs and save. The code is as follows`
import win32com.client as win32
from PIL import ImageGrab
from xlrd import open_workbook
import os
excel = win32.gencache.EnsureDispatch("Excel.Application")
wb = open_workbook('Inputs_v3.xlsm')
r = wb.sheet_by_name('Inputs')
r.CopyPicture()
im = ImageGrab.grabclipboard()
im.save('somefile.png','PNG')
` The error is as follows
'Attribute error: 'Sheet' object has no attribute 'CopyPicture''
Please suggest where I am doing wrong.Thanks in advance
Upvotes: 2
Views: 20850
Reputation: 61
Use a python library called excel2img. In one line you can take a screenshot from any excel file
import excel2img
excel2img.export_img("Excel File Full Path", "Target Image full Path", "Excel SheetName", None)
and you can identify a specific cells range as well.
import excel2img
excel2img.export_img("test.xlsx", "test.bmp", "", "Sheet2!B2:C15")
I hope this will help.
Upvotes: 6
Reputation: 6284
The following code will get you the win32com reference that you actually need to access the Excel worksheet's objects and methods:
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open('myworkbook.xlsx')
ws = wb.Worksheets('worksheet_name') # alternatively Worksheets(1) etc
Now you can do, for example:
ws.Shapes(1).CopyPicture()
I've tested this with Python 3.4, pywin32 219 and Excel 2010 on Windows 7.
Note that this doesn't involve xlrd
at all - that's a package that can read Excel files without having Excel installed on the computer, but I don't know if it supports getting images of or from Excel workbooks.
Upvotes: 2