Python win32com excel>> ws.cells(1,1)。值不起作用
我已经使用了win32com.client到Excel。
到目前为止。
但是从现在开始,该代码不起作用。 发生错误>> '< win32com.gen_py.microsoft excel 16.0对象库。对象没有属性“单元格”
是什么问题?
xlsApp = win32com.client.GetActiveObject("Excel.Application")
wb = xlsApp.Workbooks(wb_name)
ws = wb.Worksheets(ws_name)
test = ws.cells(1, 1).value
print(test)
i have used win32com.client to to something with excel.
so far, ".cells(1, 1).value" method succesfully read the value in row1, column1.
but from now, that code doesn't work.
it occurs error >>
'<win32com.gen_py.Microsoft Excel 16.0 Object Library._Worksheet instance at 0x2284591006720>' object has no attribute 'cells'
what is a problem?
xlsApp = win32com.client.GetActiveObject("Excel.Application")
wb = xlsApp.Workbooks(wb_name)
ws = wb.Worksheets(ws_name)
test = ws.cells(1, 1).value
print(test)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
方法名称为
cells()
带有大写“ C”是一个简单的答案。公平地问:“如果
cells()
以前起作用,为什么现在不起作用?”。恕我直言,这是Win32COM的失败。Win32COM将为COM对象生成包装器(使用称为
gen_py
的软件包,该软件包为每个对象创建一个Python文件)。如果存在这样的包装器,则默认情况下将使用Win32COM使用它。该包装纸对病例敏感。这是“早期约束”。如果没有包装器,则会调用
getActiveObject()
anddispatch()
将使用“晚绑定”,其中win32com将尝试在对象上调用您想要的任何方法(该方法是否存在)。该软件包采用您要求的任何方法,并尝试通过iDispatch.getIdSofNames()
从COM对象获取该函数的ID。至关重要的是,此查找是不敏感的:使用cell()
,cells()
或什至cells()
都可以使用。这就是问题。生成的包装器存储在用户目录中。您的代码可能会很乐意使用后期绑定和
cell()
,但是另一个程序可能会在以后创建包装器。现在,您的代码将看到此包装器并切换到早期绑定,现在cells()
不再有效:您需要使用cells()
。因此,当使用win32com时,总是值得从参考中找到确切的函数名称,例如从这里
The method name is
Cells()
with an uppercase ‘C’ is the simple answer.It is fair to ask: “If
cells()
worked before, why doesn’t it work now?”. IMHO it is a failing of win32com.win32com will, if asked, generate a wrapper for COM objects (using a package called
gen_py
which creates a Python file for each object). If such a wrapper exists win32com will use it by default. This wrapper is case-sensitive. This is “early binding”.If there is not a wrapper then calls like
GetActiveObject()
andDispatch()
will use “late binding” where win32com will try and call whatever method you want on the object (whether the method exists or not). The package takes whatever method you ask for and tries to get the ID of that function from the COM object viaIDispatch.GetIdsOfNames()
. Crucially, this lookup is case-INsensitive: usingcells()
,Cells()
or evencElLs()
will all work.And this is the problem. The generated wrappers are stored in the user’s directory. Your code might have been happily using late-binding and
cells()
, but another programme may have created the wrapper at a later date. Now your code will see this wrapper and switch to early-binding and nowcells()
no longer works: you need to useCells()
.So, when using win32com it is always worth finding out the exact function name from the reference, eg from here