Checking for empty cells with OpenPyXl

三世轮回 提交于 2019-12-07 19:17:19

问题


I've poured over numerous versions of this same question, but simply cannot find a working solution for looping through a group of cells and checking for empty ones.

Here's my code:

wb = openpyxl.Workbook(write_only=False)
sheet = wb.get_sheet_by_name('Sheet')
for i in range(1, 20):
    if sheet.cell(row=i, column=1).value == None or 'None':
        print('Space' + str(i))
        sheet.cell(row=i, column=1) = i
    else:
        pass

wb.save('filename.xlsx')

But for some reason it writes to the empty cells AND overwrites the cells which had values written in them.

I comment out the loop I find that if I run the code it erases everything that was manually written into the spreadsheet to begin with. Maybe that's part of the problem?

Also I'm using LibreOffice if that makes a difference


回答1:


What Charlie mentions is of course correct.

Non empty strings in Python evaluate to True, so you are actually testing if cell value is None or if bool('None'), and the later is always True, hence your condition always evaluates to True.

To address your specific case I'm not sure why you are trying to test for an empty cell with 'None'.

In case you really want to do this your condition should look like this:

if sheet.cell(row=i, column=1).value in [None,'None']

If you want test for None or an empty string, so None or '' then of course your condition should be:

if sheet.cell(row=i, column=1).value in [None,'']

Hope this gets you on the right track..



来源:https://stackoverflow.com/questions/40547394/checking-for-empty-cells-with-openpyxl

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