什么定义了 Excel.Application COM 对象连接到哪个 Excel 实例? [英] What defines which Excel instance an Excel.Application COM object connects to?

查看:25
本文介绍了什么定义了 Excel.Application COM 对象连接到哪个 Excel 实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import win32com.client as win32

excel = win32.gencache.EnsureDispatch('Excel.Application')
for wb in excel.Workbooks:
    print(wb.Name)

当我使用 Sublime Text 运行此脚本时:打印打开的工作簿的名称列表.

When I run this script using Sublime Text: A list of the names of open workbooks is printed.

当我使用 PyCharm 运行此脚本时:我得到一个空白列表.

When I run this script using PyCharm: I get a blank list.

两者都在同一台 PC 上并使用相同版本的 Python(3.5 32 位).

Both are on the same PC and are using the same version of Python (3.5 32-bit).

不确定这条信息是否有影响,但我第一次下载 PyCharm 时从未运行过 PyCharm 安装程序.我下载了 zip 文件,每次都从解压缩的文件夹中运行 PyCharm.exe.这可能是原因吗?

Not sure if this piece of info makes a difference, but I never ran the PyCharm installer when I first downloaded PyCharm. I downloaded the zip file and just run the PyCharm.exe from the unzipped folder every time. Could this be the reason why?

推荐答案

原因一定是在一种情况下,您连接到正在运行的 Excel 实例,而在另一种情况下,打开一个新实例(或连接到另一个).

The reason must be that in one case, you connect to a running Excel instance while in the other one, open a new one (or connect to some other one).

为确保连接到现有实例,您可以根据 附加到已经运行的使用 GetActiveObject 或 BindToMoniker 的应用程序中的 Office 应用程序 – .NET4Office.

To ensure connecting to an existing instance, you can use win32com.client.GetActiveObject(<ProgID>) as per Attaching to an already running Office application from your application using GetActiveObject or BindToMoniker – .NET4Office.

这些是我注意到的模式,用于控制 Excel.Application 对象连接到哪个 Excel 实例:

These are the patterns that I noticed that govern which Excel instance an Excel.Application object connects to:

  • 如果您有一个在运行程序之前手动启动的 Excel 实例,该程序将连接到该实例
  • 如果没有,excel.exe 实例由托管 DCOM 进程启动器服务的 svchost.exe 进程产生
    • 此实例最初没有任何工作簿打开
    • If you have an Excel instance that was launched by hand before running your program, the program connects to that instance
    • If not, an excel.exe instance is spawned by the svchost.exe process hosting the DCOM process launcher service
      • This instance doesn't initially have any workbooks open

      所以如果你例如从交互式控制台运行您的代码,或者 IDE 不会每次都重新启动 Python 进程(不太可能但可能),您可能有旧的现有引用.

      So if you e.g. run your code from interactive console, or the IDE doesn't restart the Python process each time (unlikely but possible), you may have old existing references.

      这篇关于什么定义了 Excel.Application COM 对象连接到哪个 Excel 实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆