[英]Can't access functions in Excel.Application().Workbooks from Python 2.7/3.5: '__ComObject' object has no attribute X
I am trying to use Microsoft.Office.Interop.Excel from a Python script: 我正在尝试通过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()
Here is the output: 这是输出:
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'
Thanks for reading. 谢谢阅读。
You can only get to COM objects from pythonnet using reflection currently: 您目前只能使用反射从pythonnet转到COM对象:
clr.AddReference("System.Reflection")
from System.Reflection import BindingFlags
excel.Workbooks.GetType().InvokeMember("Count",
BindingFlags.GetProperty |
BindingFlags.InvokeMethod,
None, excel.Workbooks, None)
Here is a wrapper function: 这是一个包装函数:
https://gist.github.com/denfromufa/ec559b5af41060c5ac318f7f59d8b415#file-excel_interop_vsto-ipynb https://gist.github.com/denfromufa/ec559b5af41060c5ac318f7f59d8b415#file-excel_interop_vsto-ipynb
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.