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 Dispa
Try this:
wbs.Close()
excel.Quit()
del excel # this line removed it from task manager in my case
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
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.
I have this in my files that use Excel:
self.excel.Application.Quit()