Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
804 views
in Technique[技术] by (71.8m points)

winapi - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...