无法访问Excel.Application()中的函数。Python 2.7 / 3.5的工作簿:“__ComObject”对象没有属性X

我正在尝试从Python脚本中使用Microsoft.Office.Interop.Excel:

import msvcrt import clr clr.AddReference("Microsoft.Office.Interop.Excel") import Microsoft.Office.Interop.Excel as Excel excel = Excel.ApplicationClass() excel.Visible = True # makes the Excel application visible to the user - will use this as True for debug excel.DisplayAlerts = False # turns off Excel alerts since I don't have a handler print ("Excel: " + str(type(excel))) print ("Workbooks: " + str(type(excel.Workbooks))) print ("Workbooks count: " + str(excel.Workbooks.Count)) #wb = excel.Workbooks.Open(r'C:\Projects\Experiments\Python\ExcelInterop\Test.xlsx') print ("Press any key") msvcrt.getch() 

这是输出:

 C:\Projects\Experiments\Python\ExcelInterop>exceltest.py Excel: <class 'Microsoft.Office.Interop.Excel.ApplicationClass'> Workbooks: <class 'System.__ComObject'> Traceback (most recent call last): File "C:\Projects\Experiments\Python\ExcelInterop\exceltest.py", line 12, in <module> print ("Workbooks count: " + str(excel.Workbooks.Count)) AttributeError: '__ComObject' object has no attribute 'Count' 
  • 我在Windows 10的pipe理员cmd提示符下运行
  • 我已经尝试了python 2.7和3.5(使用py -3 exceltest.py)。
  • Microsoft.Office.Interop.Excel是版本15.0.4420.1017(Office 2013)
  • 我创build了一个类似的.NET控制台应用程序,工作正常。
  • 我使用ILDASM检查来自Microsoft.Office.Interop.Excel的引用,然后使用gacutil -l仔细检查所有引用的程序集是否都在GAC中。
  • 以防万一,我将office.dll,stdole.dll和Microsoft.Vbe.Interop.dll复制到Python脚本正在运行的文件夹中。 如果我不embeddedMicrosoft.Office.Interop.Excel的互操作types,则这些是添加到.NET控制台应用程序生成文件夹的程序集。
  • 我已经为2.7和3.5安装了Python的.NET(从https://pypi.python.org/pypi/pythonnet )

谢谢阅读。

您目前只能使用reflection从pythonnet获取COM对象:

 clr.AddReference("System.Reflection") from System.Reflection import BindingFlags excel.Workbooks.GetType().InvokeMember("Count", BindingFlags.GetProperty | BindingFlags.InvokeMethod, None, excel.Workbooks, None) 

这是一个包装函数:

https://gist.github.com/denfromufa/ec559b5af41060c5ac318f7f59d8b415#file-excel_interop_vsto-ipynb