0

我已经看过很多关于如何写入 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 

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

4

1 回答 1

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))

于 2012-06-19T20:01:15.587 回答