Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python win32 COM closing excel workbook

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
like image 595
Razor Storm Avatar asked Jun 13 '11 23:06

Razor Storm


People also ask

How do you close an Excel File in Python?

Python has a close() method to close a file. The close() method can be called more than once and if any operation is performed on a closed file it raises a ValueError.

How do you close Excel if it is not closing?

Press Ctrl + W to close a workbook. You can close all open workbooks by holding down the Shift key as you click the Close button. If you have multiple worksheets open, you'll need to close each of them individually. The file is closed but Excel is still running.

How do I automatically close an Excel File?

Enable the workbook you want to automatically save and close after inactivity for a certain seconds, and press Alt + F11 keys to open Microsoft Visual Basic for Applications window. 5. Then after 15 seconds, there is a dialog popping out for remind you saving the workbook, and click Yes to save and close the workbook.


1 Answers

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...

like image 191
ig0774 Avatar answered Sep 21 '22 20:09

ig0774