# Close an Excel session with Python

**URL:** <https://discourse.mcneel.com/t/close-an-excel-session-with-python/613>\
**Category:** Scripting\
**Created:** [July 4, 2013, 8:01pm UTC](https://discourse.mcneel.com/t/close-an-excel-session-with-python/613 "2013-07-04T20:01:30Z")\
**Posts on this page:** 1\
**Showing post:** 12

<div class="post-metadata">

**Author:** ![AleksandarSM](https://sea3.discourse-cdn.com/mcneel/user_avatar/discourse.mcneel.com/aleksandarsm/32/635037_2.png) [@AleksandarSM](https://discourse.mcneel.com/u/AleksandarSM)\
**Post date:** [June 6, 2022, 11:55am UTC](https://discourse.mcneel.com/t/close-an-excel-session-with-python/613/12 "2022-06-06T11:55:45Z")

</div>

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](https://discourse.mcneel.com/t/end-ms-excel-process-with-python-script/118531)] )

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

I got it after reading this link on [StackOverflow](https://stackoverflow.com/a/25135685)

```auto
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

---

_[View the full topic](https://discourse.mcneel.com/t/close-an-excel-session-with-python/613)._
