Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12141

CopyPicture method of Range class failed - Python

$
0
0

I am running into the following error in Python pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'CopyPicture method of Range class failed', 'xlmain11.chm', 0, -2146827284), None) when trying to copy charts from an excel file into an email. The error however only appears sometimes. I have read some other threads relating to this error and have added a time aspect time.sleep(8) so it waits a certain amount of seconds before copy the chart after opening the excel. I have also added the excel.CutCopyMode = False which was another suggestion but nothing seems to be working consistently. I am new to python so any help would be great!

import win32com.clientimport pythoncomimport sysimport os from PIL import ImageGrabfrom datetime import datetimeimport time#Step 1 Refresh Haver Data in Average Hourly Earnings Filedef initiate_excel():    pythoncom.CoInitialize()    excel = win32com.client.DispatchEx('Excel.Application')    excel.DisplayAlerts = True      excel.workbooks.Open(r'X:DLX\DLX.XLAM')    excel.Visible = True    return exceldef close_excel(excel):    excel.Quit()    pythoncom.CoUninitialize()def get_file_location(AHE_File):    if not os.path.exists(AHE_File):        print(f'{AHE_File} does not exist')        return None    if os.path.dirname(AHE_File) == "":        return f'{os.getcwd()}\\{AHE_File}'    return AHE_Filedef run_macro(AHE_File, sub):    errorLevel = 0    file = get_file_location(AHE_File)    try:        excel = initiate_excel()        macro = f"'{AHE_File}'!{sub}"        excel.Application.Run(macro)    except:        if __name__ == '__main__':            print('Warning - potential error in Excel Macro')            errorLevel = 1        else:            raise    finally:        close_excel(excel)    return errorLevel#Step 2 Refresh Haver Data in Payrolls Filedef initiate_excel():    pythoncom.CoInitialize()    excel = win32com.client.DispatchEx('Excel.Application')    excel.DisplayAlerts = True      excel.workbooks.Open(r'X:\Quant\DLX\DLX.XLAM')    excel.Visible = True    return exceldef close_excel(excel):    excel.Quit()    pythoncom.CoUninitialize()def get_file_location(Payrolls_File):    if not os.path.exists(Payrolls_File):        print(f'{Payrolls_File} does not exist')        return None    if os.path.dirname(Payrolls_File) == "":        return f'{os.getcwd()}\\{Payrolls_File}'    return Payrolls_Filedef run_macro(Payrolls_File, sub):    errorLevel = 0    file = get_file_location(Payrolls_File)    try:        excel = initiate_excel()        macro = f"'{Payrolls_File}'!{sub}"        excel.Application.Run(macro)    except:        if __name__ == '__main__':            print('Warning - potential error in Excel Macro')            errorLevel = 1        else:            raise    finally:        close_excel(excel)    return errorLevel#Step 3 Refresh Haver Data in Payrolls Full Filedef initiate_excel():    pythoncom.CoInitialize()    excel = win32com.client.DispatchEx('Excel.Application')    excel.DisplayAlerts = True      excel.workbooks.Open(r'X:\Quant\DLX\DLX.XLAM')    excel.Visible = True    return exceldef close_excel(excel):    excel.Quit()    pythoncom.CoUninitialize()def get_file_location(Full_File):    if not os.path.exists(Full_File):        print(f'{Full_File} does not exist')        return None    if os.path.dirname(Full_File) == "":        return f'{os.getcwd()}\\{Full_File}'    return Full_Filedef run_macro(Full_File, sub):    errorLevel = 0    file = get_file_location(Full_File)    try:        excel = initiate_excel()        macro = f"'{Full_File}'!{sub}"        excel.Application.Run(macro)    except:        if __name__ == '__main__':            print('Warning - potential error in Excel Macro')            errorLevel = 1        else:            raise    finally:        close_excel(excel)    return errorLevelAHE_File = r'X:Python\Payrolls\Average_Hourly_Earnings.xlsm'Payrolls_File = r'X:Python\Payrolls\Payrolls.xlsm'Full_File = r'X:Python\Payrolls\Payrolls_Full_Table.xlsm'payrolls_table = r'X:Python\Payrolls\Payrolls_table.jpg'AHE_table = r'X:Python\Payrolls\AHE_table.jpg'Full_table = r'X:Python\Payrolls\Full_table.jpg'sub = "Macro1.RefreshData"run_macro(AHE_File, sub)run_macro(Payrolls_File, sub)run_macro(Full_File, sub)# Step 4 Take Screenshot of Payrolls Tablepythoncom.CoInitialize()excel = win32com.client.DispatchEx('Excel.Application')wb = excel.Workbooks.Open(Payrolls_File)sheet = wb.Sheets("Tables")time.sleep(5)copyrange = sheet.Range('B3:E27')excel.CutCopyMode = Falsecopyrange.CopyPicture(Appearance=1, Format=2)ImageGrab.grabclipboard().save(payrolls_table)close_excel(excel)#Step 5 Take a Screenshot of AHE Tablepythoncom.CoInitialize()excel = win32com.client.DispatchEx('Excel.Application')wb = excel.Workbooks.Open(AHE_File)sheet1 = wb.Sheets("Tables")time.sleep(5)copychart = sheet1.Range('B3:E25')excel.CutCopyMode = Falsecopychart.CopyPicture(Appearance=1, Format=2)ImageGrab.grabclipboard().save(AHE_table)close_excel(excel)#Step 6 Take a Screenshot of Full Tablepythoncom.CoInitialize()excel = win32com.client.DispatchEx('Excel.Application')wb = excel.Workbooks.Open(Full_File)sheet1 = wb.Sheets("Table")time.sleep(8)copychart = sheet1.Range('D4:G20')excel.CutCopyMode = Falsecopychart.CopyPicture(Appearance=1, Format=2)ImageGrab.grabclipboard().save(Full_table)close_excel(excel)#Step 7 Build Emailoutlook = win32com.client.Dispatch('Outlook.Application')  message = outlook.CreateItem(0)message.To = "xxx@xxx.com"Today = datetime.today()date = Today.strftime("%m/%d/%Y")message.Subject = date +" Payrolls Print"message.BodyFormat = 2 image_cid1= "Payrolls_table.jpg"image_cid2= "AHE_table.jpg"image_cid3= "Full_table.jpg"body = """<html><body><p>Hello - Please see below for a complete breakdown from todays Payroll Print. </p><meta http-equiv="Content-Type" content="text/html; charset=us-ascii"><p>Below is a table of today's payroll levels. </p><p><img src="cid:Payrolls_table.jpg"><p>Below is a table of MoM percent change in Average Hourly Earnings. </p><p><img src="cid:AHE_table.jpg"><p>Below is a summary table of payrolls. </p><p><img src="cid:Full_table.jpg"></body></html>"""attachment1 = message.Attachments.Add(r'X:Python\Payrolls\Payrolls_table.jpg')attachment2 = message.Attachments.Add(r'X:Python\Payrolls\AHE_table.jpg')attachment3 = message.Attachments.Add(r'X:Python\Payrolls\Full_table.jpg')attachment1.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "Payrolls_table.jpg")attachment2.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "AHE_table.jpg")attachment3.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "Full_table.jpg")message.HTMLBody = bodymessage.Display()

Viewing all articles
Browse latest Browse all 12141

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>