【问题标题】:Reading and analyzing data from Excel sheets using pywin32使用 pywin32 从 Excel 工作表中读取和分析数据
【发布时间】:2012-06-20 04:01:15
【问题描述】:

我已经看到很多关于如何写入 excel 的示例,而我的程序需要从现有数据中读取。我需要通读一列并从中挑选出数字(该列是空单元格,数字以任意间隔排列),然后在我到达数据末尾时中断。我现在的代码如下,其中 xlsht 是工作表名称,x 和 y 是单元格索引,地址是所有数字的列表。

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

就目前而言,它在第 2 行崩溃。我尝试使用

if xlsht.Cells(x,y).Value not None:

但这没有用。我不知道该怎么做。另外,我想验证使用

xlsht.UsedRange 

是检测工作表最后一行的正确方法。

【问题讨论】:

  • 确切的错误信息是什么?
  • @AaronDigulla 它很长,我不知道哪些部分是相关的,heres a screencap of the consol
  • 重要的部分是Exception occurred;这是明智的程序员提供有用的错误消息以帮助弄清楚发生了什么的地方...
  • 我知道。我已经说过我不知道确定单元格值的正确方法,所以在这个阶段在错误消息中编码是没有意义的。
  • 我指的是微软只招聘世界上最优秀和最聪明的人,甚至无法正确获得简单的错误消息:-(

标签: python excel pywin32


【解决方案1】:

错误消息没有提供任何有用的线索可能是什么问题。

解决方案:穷人的调试器。打印所有和任何变量,以便您查看发生了什么:

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

你明白了。如果您使用的是 Python 3.x,则需要 print('x=',repr(x))

【讨论】:

  • rigtho,这帮助我解决了一些错误。我现在坚持如何确定单元格中的内容:if str(xlsht.Cells(x,y).Value).isdigit: 没有做任何好事。我刚刚意识到这使它成为一个字符串,然后检查该字符串是否是一个数字。显然行不通:p
  • 作为注释,我尝试过的另一种方式不起作用,if xlsht.Cells(x,y).Value.isdigit:
  • 试试dir(xlsht.Cells(x,y)) - 它应该会给你一个Cells()返回的方法和属性列表。
  • 它列出了这些:['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index',你在那里看到了什么线索?我在考虑 containseq 但我不确定要比较什么
  • xlsht.Cells(x,y).__class__ 得到什么?
猜你喜欢
  • 1970-01-01
  • 2015-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多