我有多个Excel实例在运行,并且希望连接到在其中一个实例中打开的特定文件。我尝试按照Tim Golden的说明通过完整的文件名获取工作簿。这是我在iPython中所做的:
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")结果是:
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)我做错了什么?
发布于 2021-04-23 23:56:42
下面的代码在我的机器上运行良好(Windows1064位,Python Anaconda 3.6.4)。在您的示例中,您使用的文件具有不同的名称。如果这就是问题所在?
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()https://stackoverflow.com/questions/67196410
复制相似问题