9

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?

EliSquared
  • 1,149
  • 5
  • 16
  • 38
user2910705
  • 121
  • 1
  • 1
  • 6

4 Answers4

11

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.

EliSquared
  • 1,149
  • 5
  • 16
  • 38
2

I had a situation where app.quit() did not work. In this case I used app.kill() instead.

mouwsy
  • 875
  • 5
  • 15
  • With xw.App(visible=False), xlwings creates a background process (in my task manager as "C:\Program Files\Microsoft Office\Root\Office16\EXCEL.EXE" /automation -Embedding). This doesn't always go away with `app.quit()`, but seems to so far with `app.kill()`. – voracity Jun 02 '21 at 04:01
1

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.)

voracity
  • 621
  • 8
  • 5
  • This is related to: https://stackoverflow.com/questions/65189330/excel-exe-process-keeps-on-running-if-visible-false-after-any-error – mouwsy Jun 03 '21 at 12:02
0

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.