Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

python - What defines which Excel instance an Excel.Application COM object connects to?

import win32com.client as win32

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

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

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


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

  • 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
  • However, if you launch Excel by hand after that, a second instance is created. The DCOM instance takes priority.
  • An instance is not closed even after .Quit as long as there are references to it, so any further dispatches from the same process while it has references to it will get the same instance.
  • You can't connect to Excel processes running as different users (this includes with vs without elevation).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...