Can't close Excel completely using win32com on Python

后端 未结 4 606
轻奢々
轻奢々 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条回答
  •  萌比男神i
    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.

提交回复
热议问题