Search code examples
pythonexcelpandasnumpyxlwings

xlwings context manager invoking pywintypes.com_error when invoking app.kill()


The code below has a lot more functionality within it, but its basic xlwings open, save and close functionality still invokes pywintypes.com_error: (-2147023170, 'The remote procedure call failed.', None, None). Please help as I have tried a multitude of solutions and have yet to find one that works.

import xlwings as xw

def manipulation():
       with xw.App(visible=True) as app:
          wb = xw.Book(filePath)
          sheet = wb.sheets['SheetName']
          wb.save(path)
          wb.close()
          app.kill()

If anyone could help me out, or if you need more of the code please let me know. Thank you!


Solution

  • The whole point of the context manager is that you don't need to quit the app manually anymore (and it's even going to be properly cleaned up if there's an exception happening before the end of the function. So simply leave away the kill (it's part of the context manager if there's a need for it). You should also make sure to use the app object and not rely on the active app by doing app.books instead of using xw.Book. Edit: also leave away the wb.close() as xlwings requires at least one workbook open to be able to talk to Excel. It will be automatically closed by the app context manager.

    import xlwings as xw
    
    def manipulation():
        with xw.App(visible=True) as app:
           wb = app.books.open(filePath)
           sheet = wb.sheets['SheetName']
           wb.save(path)