繁体   English   中英

检查空的excel单元格(Python)

[英]Check for empty excel cell (Python)

我知道有类似的问题,但我不太明白他们的答案。 任何帮助表示赞赏。

import xlrd
path = ('E:\clean.xlsx')
wb = xlrd.open_workbook(path)
sheet = wb.sheet_by_index(0)
is_empty = None
if (sheet.cell(row=0, column=0).value) == None:
    print("empty")

如何检查我的 excel 文件中的特定单元格并检查它是否为空? 谢谢。

您可以使用sheet.cell_value(rowx=row, colx=col)检查值。 然而,该表是一个数组。 因此,如果值为空,代码将出错。 因此,您需要使用sheet.nrowssheet.ncols检查索引是否在数组内

我确信有更好的方法来检查 null 或空。 但是,以下应该有效: if sheet.nrows > row and sheet.ncols > col and sheet.cell_value(rowx=row, colx=col):

例子:

import xlrd
path = ('E:\clean.xlsx')

wb = xlrd.open_workbook(path)
sheet = wb.sheet_by_index(0)

def is_null_or_empty(sheet, row, col):
    return True if sheet.nrows > row and sheet.ncols > col and sheet.cell_value(rowx=row, colx=col) else False
  
print(f'has value for row {0} col {0}: {is_null_or_empty(sheet, 0, 0)}')
print(f'has value for row {0} col {1}: {is_null_or_empty(sheet, 0, 1)}')

输出:

has value for row 0 col 0: False
has value for row 0 col 1: True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM