I\'m using the following code to open and display a workbook within Excel:
import win32com.client as win32
excel = win32.gencache.EnsureDispatch(\'Excel.Appl
While you found a solution, consider using try/except/finally block. Currently your code will leave the Excel.exe process running in background (check Task Manager if using Windows) even if you close the visible worksheet. As an aside, in Python or any other language like VBA, any external API such as this COM interface should always be released cleanly during application code.
Below solution uses a defined function, openWorkbook()
to go two potential routes: 1) first attempts to relaunch specified workbook assuming it is opened and 2) if it is not currently opened launches a new workbook object of that location. The last nested try/except
is used in case the Workbooks.Open()
method fails such as incorrect file name.
import win32com.client as win32
def openWorkbook(xlapp, xlfile):
try:
xlwb = xlapp.Workbooks(xlfile)
except Exception as e:
try:
xlwb = xlapp.Workbooks.Open(xlfile)
except Exception as e:
print(e)
xlwb = None
return(xlwb)
try:
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = openWorkbook(excel, 'my_sheet.xlsm')
ws = wb.Worksheets('blaaaa')
excel.Visible = True
except Exception as e:
print(e)
finally:
# RELEASES RESOURCES
ws = None
wb = None
excel = None