Can't close Excel completely using win32com on Python

后端 未结 4 513
轻奢々
轻奢々 2020-12-24 02:38

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         


        
相关标签:
4条回答
  • 2020-12-24 03:19

    Try this:

    wbs.Close()
    excel.Quit()
    del excel # this line removed it from task manager in my case
    
    0 讨论(0)
  • 2020-12-24 03:23

    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 讨论(0)
  • 2020-12-24 03:26

    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 讨论(0)
  • 2020-12-24 03:40

    I have this in my files that use Excel:

    self.excel.Application.Quit()
    
    0 讨论(0)
提交回复
热议问题