Search code examples
pythonexcelwin32com

Open excel safe mode win32com - python 2.7


I am running a program using python with would open a macro enabled excel file that uses COM objects to capture the real time data from an application. I frequently end up in an Excel crash error (occurs when i run the job more than two or three times). I went through web and found that this might be due to add ins that are installed to my excel file, I followed the instructions to remove the add ins from excel but still have the problem. I am using win32com to open the excel file and here is the code that I am using. I am new to python, please share your comments to improve this code and fix this issue.

excel = win32.gencache.EnsureDispatch('Excel.Application')

wb = excel.Workbooks.Open(excel, r'C:\\pynow_futu.xlsm')

win32api.Sleep(5000)

ws = wb.Worksheets('fut')
excel.Visible = True
excel.DisplayAlerts = False
for wb in excel.Workbooks:
    ws = wb.Worksheets('fut')
    if wb.Name == 'pynow_futu.xlsm':
        print("WB:", str(wb.Name))
        wb.DoNotPromptForConvert = True
        wb.CheckCompatibility = False
        filename = "C:\\futu.csv"
        win32api.Sleep(2000)
        wb.SaveAs(filename,FileFormat=24, ConflictResolution=2)
        win32api.Sleep(1000)
        wb.Close(True)

Solution

  • The excel file got crashed because few child process from the previous run was still active and it stops from opening the new file thus it crash. Fixed it by killing the child process