2013-10-21 112 views
2

这是我的第一个问题,我有点坏蟒蛇和英语也一样,我希望你明白......Python的win32com EXCEL返回None

我通过一个Excel列的行试图周期。最后一行返回None,我的代码出了什么问题?

import win32com.client 

excel = win32com.client.Dispatch("Excel.Application") 

for n in range(1,200): 
    n=repr(n) 
    cell = "b"+ n 
    lis = (excel.ActiveWorkbook.Activesheet.Range(cell)) 
    if lis != "": 
     print(lis) 
    else: 
     print("There's nothing here") 

它为白色行打印无,而不是在这里没有什么。

非常感谢您的帮助。

+0

'无=“”'因为空行是为无明显恢复,这不:按在评论中讨论,lis应作如下分配匹配你的if如果......改成if if'lis!= None' –

回答

0

None != ""。你应该用is not运营商测试:你不应该使用!= None如其他人所说

if lis is not None: 

注意。 From PEP8

Comparisons to singletons like None should always be done with is or is not , never the equality operators.

编辑:!

lis = excel.ActiveWorkbook.Activesheet.Range(cell).GetValue() 
+0

谢谢你的回答。我尝试但结果如下:Traceback(最近一次调用最后一次): 文件“C:/ Users/************/Read.py”,第8行, lis =( excel.ActiveWorkbook.Activesheet.Range(cells)) AttributeError:'NoneType'对象没有任何属性'Activesheet' – user2903746

+0

对不起,我的错误,文件xls被关闭......但是用你的解决方案,它将打印None而不是我的白色单元格字符串.... – user2903746

+0

@ user2903746它打印“无”或打印一些空白字符串? – SheetJS

0

因为空行将返回None值而不是空字符串。

因此,其比作None类型,而不是:

if lis is not None: 
    print(lis) 
else: 
    print("There's nothing here") 

这应该只是罚款。

+0

从PEP8:'比较像None这样的单身应该总是用is或不是,从来不是平等运算符。' – SheetJS

+0

编辑,对不起。我忘了那个。 – aIKid