python win32 COM关闭excel工作簿

时间:2011-06-13 23:35:18

标签: python winapi excel com win32com

我在COM中打开几个不同的工作簿(excel xlsx格式),然后搞砸它们。随着程序的进展,我希望关闭一个特定的工作簿,但保持其余的工作簿。

如何关闭一个工作簿? (而不是整个excel应用程序)

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

3 个答案:

答案 0 :(得分:19)

工作簿COM对象has a Close() method。基本上,它应该是这样的:

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

上面只是一个框架,这里有一些代码可以在我的机器上运行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文件。但是我能够在同一个会话中成功打开和修改文件,如下所示:

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)

不知道是否有任何帮助...

答案 1 :(得分:3)

您也可以尝试使用以下代码:

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()

答案 2 :(得分:0)

import os

def closeFile():

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

    except Exception:
        print("KU")

closeFile()

我已经搜索并测试了它,非常有用