我正在使用一个 Excel 工作表,它总共有 999 行,其中 20 行是数据填充行,其他行是空的。
所以当我打印 max_rows 时,它给了我 999 个数字,而不是 20 个数字!我正在关注本教程 - openpyxl 教程
wb = openpyxl.load_workbook(path)
s = wb.active
print(s.max_row)
Run Code Online (Sandbox Code Playgroud)
如果你想使用 openpyxl,你需要自己计算它们
wb = openpyxl.load_workbook(path)
ws = wb.active
count = 0
for row in ws:
if any(cell.value is not None for cell in row):
count += 1
print(count)
Run Code Online (Sandbox Code Playgroud)
或者
wb = openpyxl.load_workbook(path)
ws = wb.active
print(len(
[row for row in ws if any(cell.value is not None for cell in row)]
))
Run Code Online (Sandbox Code Playgroud)
解释
如果某个单元格在 xlsx 中没有任何值,那么None您就可以获取它的值。cell.value is None for cell in row仅当一行根本没有任何数据时才会触发该检查。您可以轻松地交换all为any不计算具有任何空字段的行。