Close an Excel session with Python

Hi everyone,

I’ve been dealing with killing excel issue for a long time now.

( my thread with no practicable solution at that moment [End MS Excel process with python script] )

So far the best method to “kill” Excel I came up with is this one:

I got it after reading this link on StackOverflow

import rhinoscriptsyntax as rs
import clr
import System.GC

clr.AddReference("Microsoft.Office.Interop.Excel")
from Microsoft.Office.Interop import Excel

def XLS_cleanup():
    
    System.GC.Collect()
    System.GC.WaitForPendingFinalizers()
    return
    
def Excel_Open():

    myfile = rs.OpenFileName("Select Excel File:","Excel file|*.xls;*.xlsx|")

    if not myfile:
        return
  
    xl = Excel.ApplicationClass()
    WB=xl.Workbooks.Open (myfile)

    print WB.Name

    WB.Close()
    xl.Quit()

Excel_Open()
XLS_cleanup()

Note that I have intentionally violated the “two dot” rule when creating WB variable and it still works

The catch is to put the script inside the one function and the cleanup code inside another.
First you call the script function, and then the cleanup, and it works

Placing everything inside the same function did not work for me…

BR
Aleksandar Djordjic

1 Like