how to check if a cell is empty in openpyxl python

倾然丶 夕夏残阳落幕 提交于 2019-12-24 02:55:08

问题


I'm making a conditional statement in openpyxl Python to check if a cell is empty. Here's my code:

newlist = []
looprow = 1
print ("Highest col",readex.get_highest_column())
getnewhighcolumn = readex.get_highest_column()        
for i in range(0, lengthofdict):
    prevsymbol = readex.cell(row = looprow,column=getnewhighcolumn).value
    if prevsymbol == "None":
        pass
    else:
        newstocks.append(prevsymbol)
        looprow += 1
    #print (prevsymbol)
print(newlist)

I tried if prevsymbol == "": and if prevsymbol == null: to no avail.


回答1:


You compare prevsymbol with str "None", not None object. Try

if prevsymbol == None:

Also here

prevsymbol = readex.cell(row = looprow,column=getnewhighcolumn).value

you use looprow as row index. And you increment looprow only if cell.value is not empty. Here

newstocks.append(prevsymbol)

you use newstocks instead of newlist. Try this code

newlist = []
print ("Highest col",readex.get_highest_column())
getnewhighcolumn = readex.get_highest_column()        
for i in range(0, lengthofdict):
    prevsymbol = readex.cell(row = i+1,column=getnewhighcolumn).value
    if prevsymbol is not None:
        newlist.append(prevsymbol)
print(newlist)



回答2:


Take the quotes away from the None.

if prevsymbol is None:

This is the python equivalent of checking if something is equal to null.



来源:https://stackoverflow.com/questions/31475811/how-to-check-if-a-cell-is-empty-in-openpyxl-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!