python win32 COM关闭excel工作簿 [英] python win32 COM closing excel workbook
问题描述
我在COM中打开几个不同的工作簿(excel xlsx格式),并与他们混淆。随着计划的进行,我希望关闭一个特定的工作簿,但打开其余的工作簿。
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.
如何关闭一个工作簿? (而不是整个excel应用程序)
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
推荐答案
工作簿COM对象有一个Close()方法。基本上,它应该是:
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
上面只是一个框架,这里的一些代码在我的机器上对Office 2010有效:
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')
当然,新的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)
< t知道是否有任何帮助...
Don't know if any of that helps...
这篇关于python win32 COM关闭excel工作簿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!