确定工作表在openpyxl中是否为空 [英] Determine if worksheet is empty in openpyxl

查看:945
本文介绍了确定工作表在openpyxl中是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,如果有数据,我将工作表写入最后一列+ 2,如果工作表为空,则写入最后一列+ 1.我得到的是一个空的工作表,如下所示:

I have an application where I write to a worksheet to the last column + 2 if there is already data and to the last column + 1 if the worksheet is empty. I get what I think is an empty worksheet as follows:

from openpyxl.workbook.workbook import Workbook
book = Workbook()
sheet = book.active

当我执行sheet.max_rowsheet.max_column时,两个属性都得到1.我想得到零,所以我要执行以下操作:

When I do sheet.max_row and sheet.max_column, I get 1 for both properties. I would like to get zero, so I do the following:

if sheet.max_row == 1 and sheet.max_column == 1 and not sheet['A1'].value:
    start_col = 1
else:
    start_col = sheet.max_column + 2

必须检查单元格的值似乎有点过大,更不用说容易出错了.我最初希望以下方法能起作用:

Having to check the value of the cell seems a bit overkill, not to mention error-prone. I initially expected the following to work:

if sheet.max_column == 0:
    start_col = 1
else:
    start_col = sheet.max_column + 2

是否有原因max_rowmax_column始终为>= 1?这是错误,故意的功能还是其他东西的合理副作用?最后,有没有解决方法(例如sheet.isempty()之类的东西).

Is there a reason max_row and max_column are always >= 1? Is this a bug, an intentional feature or a reasonable side-effect of something else? Finally, is there a workaround (e.g. something like sheet.isempty()).

顺便说一句,我在浏览错误跟踪器时发现以下评论:

By the way, I found the following comment while browsing the bug tracker: https://bitbucket.org/openpyxl/openpyxl/issues/514/cell-max_row-reports-higher-than-actual#comment-21091771:

具有空单元格的行仍然是行.我们可能不知道它们可能会被格式化以备将来使用或用于其他用途. 2.3略有改进,但仍将包含成排的空单元格.

Rows with empty cells are still rows. They might be formatted for future use or other stuff, we don't know. 2.3 has slightly improved heuristics but will still contain rows of empty cells.

这(以及我无法找到其链接的另一条评论)使我相信第一个单元实际上一直存在.在这种情况下,是否值得提交功能请求?

This (and another comment I can no longer find a link for) lead me to believe that the first cell effectively always exists. In this case, is it worth submitting a feature request?

推荐答案

确定工作表是否为空"的唯一可靠方法是查看_cells属性.但是,这是内部API的一部分,可能会更改.实际上,几乎可以肯定会发生变化.

The only reliable way to determine if a worksheet is "empty" is to look at the _cells attribute. However, this is part of the internal API and liable to change. In fact it is almost certain to change.

max_rowmax_column属性在内部用于计数器,并且必须为1或更大.

The max_row and max_column attributes are used internally for counters and must be 1 or more.

没有相关代码和测试的功能请求将被拒绝,并且我对总体上空"工作表的想法持相当怀疑的态度.

A feature request without relevant code and tests would be rejected and I'm fairly sceptical about the idea of "empty" worksheet in general.

这篇关于确定工作表在openpyxl中是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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