I am trying to save the chart from Excel as an image file in Python. I am using WIn32com, the chart is getting exported as required but when I am trying to delete the ActiveSheet,it is giving me the error.
excel.ActiveSheet().Delete()
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 192, in __call__
return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
pywintypes.com_error: (-2147352573, 'Member not found.', None, None)
Any help to overcome this error?
Below is my code:
import win32com.client as win32
def saveChart():
excel = win32.Dispatch("Excel.Application")
wb = excel.Workbooks.Open(r'C:\Users\projects\Rating.xlsx')
selection = "A1:K16"
xl_range = wb.Sheets("Categories").Range(selection)
excel.ActiveWorkbook.Sheets.Add().Name="image_sheet"
cht = excel.ActiveSheet.ChartObjects().Add(0,0,xl_range.Width, xl_range.Height)
xl_range.CopyPicture()
cht.Chart.Paste()
cht.Chart.Export(r'C:\Users\projects\MyExportedChart.png')
excel.DisplayAlerts = False
cht.Delete()
excel.ActiveSheet.Delete()
excel.DisplayAlerts = True
excel.ActiveWorkbook.Close()
I took the code from Export Charts from Excel as images using Python
Updated the code,which worked
Is ActiveSheet
a field, like you're using it here:
cht = excel.ActiveSheet.ChartObjects().Add(0,0,xl_range.Width, xl_range.Height)
Or a method like you're using it here:
excel.ActiveSheet().Delete()
Since the first call doesn't give you the error, and the error says that the member is not found, I'm going to guess that the second one is wrong, and should be:
excel.ActiveSheet.Delete()