为什么我基于哪个IDE执行代码在Excel COM中获得打开的工作簿的不同列表? [英] Why do I get different lists of open workbooks in Excel COM based on which IDE executes the code?

查看:56
本文介绍了为什么我基于哪个IDE执行代码在Excel COM中获得打开的工作簿的不同列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

要确保连接到现有实例,可以按照

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.

我不确定什么时候会发生,但是这些是我注意到的模式,可以解释您看到的内容:

I'm not completely sure when either happens, but these are the patterns I noticed that may explain what you see:

  • 如果您有一个在运行程序之前手动启动的Excel实例,则程序会连接到该实例
  • 如果不是,则由托管DCOM进程启动器服务的svchost.exe进程派生excel.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.

      这篇关于为什么我基于哪个IDE执行代码在Excel COM中获得打开的工作簿的不同列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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