【问题标题】:Excel not closing using the COM in Python在 Python 中使用 COM 不关闭 Excel
【发布时间】:2023-01-24 02:53:15
【问题描述】:

我的 Excel 工作簿没有通过执行突出显示的最后一条语句关闭。但是抛出如下错误。

我的代码....

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')

excel.Visible= True

excelApl = excel.Application.Workbooks.Open ("C:\Technical\AutomationScripts\TestExcelCOM.xlsx")
a = excelApl.Worksheets("Sheet1").Range("A2").Value = "Stay with me"
a = excelApl.Worksheets("Sheet1").Range("A2").Value
print(a)
a = excelApl.Worksheets("Sheet1").Range("A2").Value = "Hello"
print(a)

**excel.Application.Workbooks("C:\Technical\AutomationScripts\TestExcelCOM.xlsx").Close**

最后一条语句抛出以下错误....

pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
>>> Stay with me
Hello
Traceback (most recent call last):
  File "C:\Program Files\Python39\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 363, in RunScript
    exec(codeObject, __main__.__dict__)
  File "C:\Technical\AutomationScripts\Testscript.py", line 13, in <module>
    excel.Application.Workbooks("C:\Technical\AutomationScripts\TestExcelCOM.xlsx").Close
  File "C:\Users\jpillai1\AppData\Local\Temp\gen_py\3.9\00020813-0000-0000-C000-000000000046x0x1x9\Workbooks.py", line 198, in __call__
    ret = self._oleobj_.InvokeTypes(0, LCID, 2, (13, 0), ((12, 1),),Index
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
>>> 

想关闭工作簿。

【问题讨论】:

    标签: python excel win32com office-automation excel-automation


    【解决方案1】:

    Workbooks 属性返回一个代表所有打开的工作簿的 Workbooks 集合。对象的名称或索引号可用于检索特定工作簿实例,但文件路径如代码中所示:

    excel.Application.Workbooks("C:TechnicalAutomationScriptsTestExcelCOM.xlsx").Close
    

    考虑使用 ActiveWorkbook 属性,它返回一个 Workbook 对象,代表活动窗口(顶部的窗口)中的工作簿。因此,代码可以按以下方式重写:

    excel.Application.ActiveWorkbook.Close
    

    或者简单地:

    excelApl.Close
    

    始终处理从 Open 方法中检索到的对象实例。

    【讨论】: