14

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
Razor Storm
  • 12,167
  • 20
  • 88
  • 148

4 Answers4

37

The the Workbook COM object has a Close() method. Basically, it should be something like:

xl = Dispatch('Excel.Application')
wb = xl.Workbooks.Open('New Workbook.xlsx')
# do some stuff
wb.Close(True) # save the workbook

The above was just a skeleton here's some code that works on my machine against Office 2010:

from win32com.client import Dispatch
xl = Dispatch('Excel.Application')
wb = xl.Workbooks.Add()
ws = wb.Worksheets.Add()
cell = ws.Cells(1)
cell.Value = 'Some text'
wb.Close(True, r'C:\Path\to\folder\Test.xlsx')

Of course, that creates a new xlsx file. But then I'm able to successfully open and modify the file in the same session as follows:

wb = xl.Workbooks.Open(r'C:\Path\to\folder\Test.xlsx')
ws = wb.Worksheets(1)
cell = ws.Cells(2)
cell.Value = 'Some more text'
wb.Close(True)

Don't know if any of that helps...

ig0774
  • 39,669
  • 3
  • 55
  • 57
  • @RazorStorm: What version of Excel / Office are you using? See my slightly longer examples. – ig0774 Jun 15 '11 at 12:43
  • Weird... it works now. I guess I wrote it wrong when I tested it earlier or something. – Razor Storm Jun 15 '11 at 23:06
  • Must first install package `pywin32` from https://github.com/mhammond/pywin32. For examples, of how to use, https://github.com/mhammond/pywin32/blob/master/pywin32_testall.py. Must use `import win32api` before running this script. – Contango Mar 22 '19 at 13:57
  • Notice that in case the workbook has "on save" event handlers, it is possible (in Excel Office 365) that `Close(True)` unintuitively manages to close the workbook before it's saved; in those cases `wb.Save(); wb.Close()` is safer. – fuglede Dec 10 '20 at 12:56
10

You can also try to use the following code:

excel = Dispatch("Excel.Application")
excel.Visible = False
workbook = excel.Workbooks.Open(fileName)

# with saving
excel.DisplayAlerts = False
if saveAs:
    excel.ActiveWorkbook.SaveAs(fullFileNameToSave)
else:
    excel.ActiveWorkbook.Save()
excel.Quit()

#without saving

map(lambda book: book.Close(False), excel.Workbooks)
excel.Quit()
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52
1

This function closes any opened excel file

import os

def closeFile():

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

    except Exception:
        print("KU")

closeFile()
-2
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)
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • 7
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Adrian Mole Sep 14 '21 at 12:16
  • 2
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 14 '21 at 12:33