Skip to content

Instantly share code, notes, and snippets.

@Furao
Created November 7, 2011 18:36
Show Gist options
  • Save Furao/1345767 to your computer and use it in GitHub Desktop.
Save Furao/1345767 to your computer and use it in GitHub Desktop.
Safely handle excel instances in windows
import win32com.client as win32
file_path = 'C:\\File.xlsx'
already_open = False
# Open excel application and template workbook
xl = win32.gencache.EnsureDispatch("Excel.Application")
# Check to see if a workbook is already open
if len(xl.Workbooks) > 0:
already_open = True
xl.Visible = False
try:
wb = xl.Workbooks.Open(file_path)
# Use workbook as needed ...
wb.Close()
except:
print 'Error opening file'
finally:
if already_open:
# Since it was already open, make it visible again so you don't close out other workbooks
xl.Visible = True
else:
# Quit excel since there are no other workbooks open
xl.Application.Quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment