使用OpenPyXl检查空单元格 [英] Checking for empty cells with OpenPyXl

查看:223
本文介绍了使用OpenPyXl检查空单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经提出了相同问题的多个版本,但是根本找不到用于循环浏览一组单元格并检查空单元格的有效解决方案.

这是我的代码:

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

但是由于某种原因,它会写入空单元格并覆盖其中已写入值的单元格.

我注释掉了循环,发现如果我运行代码,它将擦除手动写入电子表格的所有内容.也许这是问题的一部分?

如果这有所作为,我也正在使用LibreOffice

解决方案

查理提到的内容当然是正确的.

Python中的非空字符串求值为True,因此您实际上正在测试单元格值是否为None或bool('None'),而后者始终为True,因此您的条件始终求值为True. /p>

要解决您的具体情况,我不确定为什么您要尝试使用'None'测试一个空单元格.

如果您确实要执行此操作,则您的情况应如下所示:

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

如果您要测试None或空字符串,那么None or ''那么您的条件当然应该是:

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

希望这能使您走上正确的轨道.

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

解决方案

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

这篇关于使用OpenPyXl检查空单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆