'I cannot close Excel 2016 after executing a xlwings function
when I execute a an Xlwings function I can save and close the workbook. But I cannot close Excel 2016 anymore. Is this a known issue? How can I fix this?
Solution 1:[1]
Here is how I got it to work:
import xlwings as xw
wbPath = [WorkbookPath]
wb = xw.Book(wbPath)
app = xw.apps.active
wb.save(wbPath)
#wb.close()
app.quit()
Note that I commented out the line wb.close(). You can skip this step and instead set the app = active Excel instance, save the workbook, and then quit the app.
Solution 2:[2]
I had a situation where app.quit() did not work. In this case I used app.kill() instead.
Solution 3:[3]
Just to build on mouwsy's answer, I now have this context manager:
class XwApp(xw.App):
def __enter__(self, *args, **kwargs):
return super(*args, **kwargs)
def __exit__(self, *args):
for book in self.books:
try:
book.close()
except: pass
self.kill()
which I use like so:
with XwApp(visible=False) as app:
app.books.add()
# or
app.books.open('file.xlsx')
# ...
and this seems reasonably clean exiting so far. (But pre-opened Excel windows can always mess things up.)
Solution 4:[4]
I know this is old but I was unable to find an answer that worked and figured out a solve. I was able to close the instance of Excel by accessing the api property in xlwings.
xl = xw.apps.active.api
xl.Quit()
xlwings is just a fancy wrapper around pywin32, you can directly access the pywin32 functions by implementing the api property.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | Tyler Anderson |
