Python 使用pywin32从Excel工作表读取和分析数据
我已经看过很多关于如何编写excel的例子,我的程序需要从现有数据中读取数据。我需要通读一列并从中选择数字(该列为空单元格,以任意间隔显示数字),然后在到达数据末尾时中断。下面是我的代码,其中xlsht是表名,x和y是单元格索引,address是所有数字的列表Python 使用pywin32从Excel工作表读取和分析数据,python,excel,pywin32,Python,Excel,Pywin32,我已经看过很多关于如何编写excel的例子,我的程序需要从现有数据中读取数据。我需要通读一列并从中选择数字(该列为空单元格,以任意间隔显示数字),然后在到达数据末尾时中断。下面是我的代码,其中xlsht是表名,x和y是单元格索引,address是所有数字的列表 while y < xlsht.UsedRange: if str(xlsht.Cells(x,y).Value).isdigit: address.append(xlsht.Cells(x,y).Value
while y < xlsht.UsedRange:
if str(xlsht.Cells(x,y).Value).isdigit:
address.append(xlsht.Cells(x,y).Value)
y += 1
continue
else:
y += 1
return address
但那没用。我不知道还能怎么做。此外,我还想验证使用
xlsht.UsedRange
是检测工作表最后一行的正确方法。错误消息没有提供任何有用的线索,说明问题可能是什么 解决方案:可怜人的调试器。打印所有和任何变量,以便查看发生的情况:
print 'xlsht=',xlsht
print 'x=',x
print 'usedRange=',xlsht.UsedRange
while y < xlsht.UsedRange:
print 'y=',y
print 'cell=',xlsht.Cells(x,y)
print 'value=',xlsht.Cells(x,y).Value
if str(xlsht.Cells(x,y).Value).isdigit:
address.append(xlsht.Cells(x,y).Value)
y += 1
continue
else:
y += 1
return address
打印“xlsht=”,xlsht
打印“x=”,x
打印“usedRange=”,xlsht.usedRange
当y
你明白了。如果您使用的是Python3.x,您将需要
print('x=',repr(x))
确切的错误消息是什么?@AaronDigulla很长,我不知道哪些部分是相关的,重要的部分是异常发生
;这是一个明智的程序员放置有用错误消息的地方,有助于找出发生了什么…我知道。我已经说过,我不知道确定单元格值的正确方法,因此在这个阶段,在错误消息中进行编码是毫无意义的。我指的是,微软只雇佣了世界上最好、最聪明的人,甚至连一条简单的错误消息都没有得到:-(rigtho,这帮我解决了一些bug。我现在一直在研究如何确定单元格中的内容:if str(xlsht.Cells(x,y).Value).isdigit:
没有任何作用。我刚刚意识到这使它成为一个字符串,然后检查该字符串是否是数字。显然不起作用:作为注释,我尝试的另一种方式不起作用,如果xlsht.Cells(x,y).Value.isdigit:
尝试dir(xlsht.Cells(x,y))
-这将为您提供单元格()返回的任何内容的方法和属性列表。
将列出这些:“UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"新","新","减少","减少","减少","减少","报告","新","减少","减少,你在那里看到了什么线索吗?我在想包含或eq
,但我不确定与xlsht.Cells(x,y)相比你得到了什么?
print 'xlsht=',xlsht
print 'x=',x
print 'usedRange=',xlsht.UsedRange
while y < xlsht.UsedRange:
print 'y=',y
print 'cell=',xlsht.Cells(x,y)
print 'value=',xlsht.Cells(x,y).Value
if str(xlsht.Cells(x,y).Value).isdigit:
address.append(xlsht.Cells(x,y).Value)
y += 1
continue
else:
y += 1
return address