簡體   English   中英

無法從Python 2.7 / 3.5訪問Excel.Application()。Workbooks中的函數:'__ComObject'對象沒有屬性X

[英]Can't access functions in Excel.Application().Workbooks from Python 2.7/3.5: '__ComObject' object has no attribute 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的admin cmd提示符下運行
  • 我已經嘗試了python 2.7和3.5(使用py -3 exceltest.py)。
  • Microsoft.Office.Interop.Excel是15.0.4420.1017版本(Office 2013)
  • 我創建了一個類似的.NET控制台應用程序,效果很好。
  • 我使用ILDASM檢查來自Microsoft.Office.Interop.Excel的引用,然后使用gacutil -l再次檢查所有引用的程序集是否在GAC中。
  • 以防萬一,我將office.dll,stdole.dll和Microsoft.Vbe.Interop.dll復制到了運行Python腳本的文件夾中。 如果我不為Microsoft.Office.Interop.Excel嵌入互操作類型,則這些是添加到.NET控制台應用程序構建文件夾中的程序集。
  • 我已經為2.7和3.5安裝了用於Python的.NET(來自https://pypi.python.org/pypi/pythonnet

謝謝閱讀。

您目前只能使用反射從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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM