python win32 COM closing excel workbook

Viewed 76433

I open several different workbooks (excel xlsx format) in COM, and mess with them. As the program progresses I wish to close one specific workbook but keep the rest open.

How do I close ONE workbook? (instead of the entire excel application)

xl = Dispatch("Excel.Application")
xl.Visible = False
try:
    output = xl.Workbooks.Open(workbookName)
    output2 = xl.Workbooks.Open(workbook2Name)
except com_error:
    print "you screwed up blahblahblah"
    exit()

#work on some stuff
#close output but keep output2 open
4 Answers

This function closes any opened excel file

import os

def closeFile():

    try:
        os.system('TASKKILL /F /IM excel.exe')

    except Exception:
        print("KU")

closeFile()
def setAutoFilter(self,ws,AmountToMatch):
        amounttopass = f"{AmountToMatch}"
        print("The Amount  of that month is  ::",amounttopass)
        ws.Range("B:G").AutoFilter(Field=6, Criteria1=amounttopass,VisibleDropDown=False)
        time.sleep(timeout)
Related