Microsoft.Office.Interop.Excel工作簿在python中没有Open方法



我知道还有其他方法或模块可以用python读/写xls。我见过Autodesk Dynamo(使用IronPython(可以使用Microsoft.Office.Interop.Excel相关代码打开xls。因此,出于测试目的,我尝试在PyCharm中做类似的事情。但是,会弹出一些错误。

我选择了一台为Office安装了KMSpico的计算机。那台电脑安装了Python 3.7.x我已经安装了pythonnet

我在PyCharm中尝试了以下代码:

import clr
# clr.AddReference("Microsoft.Office.Interop.Excel") # System.IO.FileNotFoundException: Unable to find assembly 'Microsoft.Office.Interop.Excel'.
# I find a dll in C:WindowsassemblyGAC_MSILMicrosoft.Office.Interop.Excel15.0.0.0__71e9bce111e9429c
clr.AddReference("Microsoft.Office.Interop.Excel, Culture=neutral, Version=15.0.0.0, PublicKeyToken=71e9bce111e9429c")
import Microsoft.Office.Interop.Excel as Excel
excel = Excel.ApplicationClass()
print(excel.Workbooks) # System.__ComObject
print(dir(excel.Workbooks)) # ['CreateObjRef', 'Equals', 'Finalize', 'GetHashCode', 'GetLifetimeService', 'GetType', 'InitializeLifetimeService', 'MemberwiseClone', 'Overloads', 'ReferenceEquals', 'ToString', '__call__', '__class__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__overloads__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__']
wb = excel.Workbooks.Open(r'C:Usersuser123Desktopsourcetext.xlsx') # AttributeError: '__ComObject' object has no attribute 'Open'

我不确定为什么dll没有打开功能

在寻找解决方案时,我遇到了您未回答的问题。我需要用反复尝试的解决方案来填补一些空白。不管怎样,它奏效了--不知怎么的,原因是泛型类型<class'系统__ComObject'>。我认为蟒蛇网内部的一些映射魔法在这里不太好。我无法访问C:\Windows\assembly\GAC_MSIL中的dll。根据用pythonnet导入DLL,我使用以下方法加载DLL:

import System
from System import Reflection
exceldll = "C:/Program Files (x86)/Microsoft Office/root/Office.../Microsoft.Office.Interop.Excel.dll"
Reflection.Assembly.LoadFile(exceldll)

之后,以下导入操作正常:

from Microsoft.Office.Interop import Excel
from Microsoft.Office.Interop.Excel import Workbooks, Sheets, Range, Worksheet

在启动实际的Exel AplicationexcelApp = Excel.Application()之后,我需要从System强制对象类型__ComObject到任何需要的

wbs = Workbooks(excelApp.Application.Workbooks)
wb = wbs.get_Item(1) # .Item() is not mapped, at least .get_Item() return correct type
wss = Sheets(wb.Sheets) # wb.Sheets woulb be generic type System.__ComObject
ws = Worksheet(wss.get_Item(1)) # leftmost worksheet 
cells = Range(ws.Cells)
singleCell = Range(cells.get_Item(3,5)) # even get_Item() returns System.__ComObject here
singleValue = singleCell.get_Value() 

此外https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.applicationclass?view=excel-pia表示,这是仅供内部使用的。因此,通过excel = Excel.Application()实例化excel对象可能更安全。

最新更新