22
votes

This is my code, and I found many answers for VBA, .NET framework and is pretty strange. When I execute this, Excel closes.

from win32com.client import DispatchEx
excel = DispatchEx('Excel.Application')
wbs = excel.Workbooks
wbs.Close()
excel.Quit()
wbs = None
excel = None # <-- Excel Closes here

But when I do the following, it does not close.

excel = DispatchEx('Excel.Application')
wbs = excel.Workbooks
wb = wbs.Open('D:\\Xaguar\\A1.xlsm')
wb.Close(False)
wbs.Close()
excel.Quit()
wb = None
wbs = None
excel = None  # <-- NOT Closing !!!

I found some possible answer in Stack Overflow question Excel process remains open after interop; traditional method not working. The problem is that is not Python, and I don't find Marshal.ReleaseComObject and GC. I looked over all the demos on ...site-packages/win32com and others.

Even it does not bother me if I can just get the PID and kill it.

I found a workaround in Kill process based on window name (win32).

May be not the proper way, but a workround is:

def close_excel_by_force(excel):
    import win32process
    import win32gui
    import win32api
    import win32con

    # Get the window's process id's
    hwnd = excel.Hwnd
    t, p = win32process.GetWindowThreadProcessId(hwnd)
    # Ask window nicely to close
    win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
    # Allow some time for app to close
    time.sleep(10)
    # If the application didn't close, force close
    try:
        handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p)
        if handle:
            win32api.TerminateProcess(handle, 0)
            win32api.CloseHandle(handle)
    except:
        pass

excel = DispatchEx('Excel.Application')
wbs = excel.Workbooks
wb = wbs.Open('D:\\Xaguar\\A1.xlsm')
wb.Close(False)
wbs.Close()
excel.Quit()
wb = None
wbs = None
close_excel_by_force(excel) # <--- YOU #@#$# DIEEEEE!! DIEEEE!!!
5
Try adding the line excel.DisplayAlerts = False before the call to wbs.Open(...) and see if that helps. - srgerg
:/ not working, is a real pain excel and COM - sacabuche
I find the way but no using COM - sacabuche
The quicker, cleaner, easier answer is here: stackoverflow.com/a/18421814 - Tom

5 Answers

10
votes

Try this:

wbs.Close()
excel.Quit()
del excel # this line removed it from task manager in my case
3
votes

I have this in my files that use Excel:

self.excel.Application.Quit()
1
votes

What worked for me was making sure to de-reference any variables that you assigned along the way like so:

import win32com.client as win32

fileDirectory = 'Hello World.xlsx'

#excelFile = win32.Dispatch('Excel.Application')
excelFile = win32.gencache.EnsureDispatch('Excel.Application')

excelFile.Visible = True
excelFile.DisplayAlerts = True

wb = excelFile.Workbooks.Open(fileDirectory)
ws = wb.Sheets("Sell")

ws.Range("D1").Value = "Hello World!"
ws = None

wb.Close(False)
wb = None

excelFile.Quit()
excelFile = None

It worked with either Dispatch format.

0
votes

Python should handle the lifecycle of the COM object. Just set excel = None. See this for reference:

# CH9 says: Python manages COM lifetimes automatically for you; when your excel 
#           variable is no longer used, Excel automatically closes. In Python,
#           the simplest way to remove this variable is to assign it to another 
#           value. If you use the following code, notice that Excel vanishes 
#           from the screen; it knows there are no longer any programs referring to it. 

src:

http://www.icodeguru.com/WebServer/Python-Programming-on-Win32/ch05.htm#:~:text=xl%20=%20None

0
votes

I have fond that killing an Excel process through win32com is not always that reliable. These include excel.Application.Quit(), and del excel as suggested above.

I found the only way to make sure it is dead is to physically kill the EXCEL.EXE process:

import psutil

def kill_excel():
    for proc in psutil.process_iter():
        if proc.name() == "EXCEL.EXE":
            proc.kill()

Downside is that this script will obviously kill all excel process currently running. IF you can live with this, then this is not a bad option.