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)
JavaScript
x
12
12
1
xl = Dispatch("Excel.Application")
2
xl.Visible = False
3
try:
4
output = xl.Workbooks.Open(workbookName)
5
output2 = xl.Workbooks.Open(workbook2Name)
6
except com_error:
7
print "you screwed up blahblahblah"
8
exit()
9
10
#work on some stuff
11
#close output but keep output2 open
12
Advertisement
Answer
The the Workbook COM object has a Close() method. Basically, it should be something like:
JavaScript
1
5
1
xl = Dispatch('Excel.Application')
2
wb = xl.Workbooks.Open('New Workbook.xlsx')
3
# do some stuff
4
wb.Close(True) # save the workbook
5
The above was just a skeleton here’s some code that works on my machine against Office 2010:
JavaScript
1
8
1
from win32com.client import Dispatch
2
xl = Dispatch('Excel.Application')
3
wb = xl.Workbooks.Add()
4
ws = wb.Worksheets.Add()
5
cell = ws.Cells(1)
6
cell.Value = 'Some text'
7
wb.Close(True, r'C:PathtofolderTest.xlsx')
8
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:
JavaScript
1
6
1
wb = xl.Workbooks.Open(r'C:PathtofolderTest.xlsx')
2
ws = wb.Worksheets(1)
3
cell = ws.Cells(2)
4
cell.Value = 'Some more text'
5
wb.Close(True)
6
Don’t know if any of that helps…