Created
November 7, 2011 18:36
-
-
Save Furao/1345767 to your computer and use it in GitHub Desktop.
Safely handle excel instances in windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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