python openpyxl max_row 统计所有行而不是统计非空行

标签 python openpyxl

我正在使用一个 Excel 表,它总共有 999 行,其中 20 行是数据填充行,其他行是空的。

所以当我打印 max_rows 时,它给了我 999 个数字而不是 20 个数字!我正在关注本教程 - openpyxl tutorial

wb = openpyxl.load_workbook(path)
s = wb.active
print(s.max_row)

最佳答案

如果你想使用openpyxl,你需要自己计算它们

wb = openpyxl.load_workbook(path)
ws = wb.active
count = 0
for row in ws:
    if not all([cell.value is None for cell in row]):
        count += 1

print(count)

或者

wb = openpyxl.load_workbook(path)
ws = wb.active
print(len([row for row in ws if not all([cell.value is None for cell in row])]))

解释

如果一个单元格在 xlsx 中没有任何值,则当您获取它的值时它是 None。检查 cell.value is None for cell in row 只有在一行根本没有任何数据时才会触发。您可以轻松地将 all 替换为 any 以不计算具有任何空字段的行。

关于python openpyxl max_row 统计所有行而不是统计非空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56322053/

相关文章:

Python - 从Excel列列表创建多个文件夹

python - Openpyxl load_workbook 和保存时间太长

python - openpyxl将列变成一行

python - 如何从 IronPython 更新 WPF DataGrid 一行的值?

python - 了解 gc.get_referrers

python - 将函数内部的变量传递给函数外部的变量

python - 在 django url 中传递数组

Python xlsxwriter : use a for loop to write from several lists

python - 在 python 中读取 .xlsx 格式

python - 如何使用 openpyxl 在 Excel 中使用格式为 'yyyy-mm-dd hh:mm:ss' 的日期时间对象格式化单元格