首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用win32将Python连接到打开的Excel工作簿?

如何使用win32将Python连接到打开的Excel工作簿?
EN

Stack Overflow用户
提问于 2021-04-21 20:55:21
回答 1查看 280关注 0票数 0

我有多个Excel实例在运行,并且希望连接到在其中一个实例中打开的特定文件。我尝试按照Tim Golden的说明通过完整的文件名获取工作簿。这是我在iPython中所做的:

代码语言:javascript
复制
import win32com.client as win32
xl1 = win32.Dispatch("Excel.Application")
xl1.Visible = False
wb1 = xl1.Workbooks.Add()
wb1.SaveAs(r"C:\Users\[...]\test.xlsx")
xl2 = win32.DispatchEx("Excel.Application")
wb2 = win32.GetObject(r"C:\Users\[...]]\test.xlsm")

结果是:

代码语言:javascript
复制
Traceback (most recent call last)
<ipython-input-22-471d068eb257> in <module>
----> 1 wb2 = win32.GetObject(r"C:\Users\[...]\test.xlsm")

c:\users\[...]\venv\lib\site-packages\win32com\client\__init__.py in GetObject(Pathname, Class, clsctx)
     70     return GetActiveObject(Class, clsctx)
     71   else:
---> 72     return Moniker(Pathname, clsctx)
     73
     74 def GetActiveObject(Class, clsctx = pythoncom.CLSCTX_ALL):

c:\users\[...]\venv\lib\site-packages\win32com\client\__init__.py in Moniker(Pathname, clsctx)
     85     Python friendly version of GetObject's moniker functionality.
     86   """
---> 87   moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
     88   dispatch = moniker.BindToObject(bindCtx, None, pythoncom.IID_IDispatch)
     89   return __WrapDispatch(dispatch, Pathname, clsctx=clsctx)

com_error: (-2147221014, 'Moniker cannot open file', None, None)

我做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-23 23:56:42

下面的代码在我的机器上运行良好(Windows1064位,Python Anaconda 3.6.4)。在您的示例中,您使用的文件具有不同的名称。如果这就是问题所在?

代码语言:javascript
复制
import win32com.client as win32
FileName = r"c:\toolbox\erase\auto.xlsx"
xl1 = win32.Dispatch("Excel.Application")
xl1.Visible = False
wb1 = xl1.Workbooks.Add()
wb1.SaveAs(FileName)
xl2 = win32.DispatchEx("Excel.Application")
wb2 = win32.GetObject(FileName)
print(wb2.Name)
xl1.Quit()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67196410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档