无法让 OpenPyXl 删除行 [英] Can't get OpenPyXl to delete rows

查看:152
本文介绍了无法让 OpenPyXl 删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 和 OpenPyXL 来合并两个 Excel 报告.当报告有一行全为零值时,应删除该行.

I'm using Python and OpenPyXL to merge two Excel reports. When a report has a row of all zero values, that row should be deleted.

删除行的命令看起来很简单,但它根本不起作用.另一篇文章 建议删除行与 不兼容追加.我没有使用这个功能,但也许还有其他挑剔的地方?

The command to delete rows seems simple enough, but it simply doesn't work. Another post suggests delete rows doesn't play nice with append. I'm not using this function, but maybe there are other finicky bits?

我正在处理打开和保存操作组的 Excel 文件.这是我要删除这些行的块的代码注释版本.

I'm processing the Excel files opening and saving groups of actions. Here is a comment-for-code version of the block where I'm deleting these rows.

# Get WB
# Get WS
i = 0
del_rows = []
for row in ws.iter_rows():
    i += 1
    if row[0].value is None:
        # INVALID DATA ROW - BLANK ROW
    else:
        rowcellvals = []
        j = 0
        for cell in row:
            j += 1
            if cell.value == row[0].value:
                # INVALID COLUMN VAL - SKIP ACC NAME COL
                continue
            elif cell.value is None:
                # SKIP TITLE ROWS
                break
            else:
                # VALID DATA ROW
                if j % 2 == 0:
                    rowcellvals.append(cell.value)

        if not rowcellvals:
            continue
        else:
            if sum(rowcellvals) == 0:
                del_rows.append(i)

for r in del_rows:
       ws.delete_rows(r, 1)

# SAVE

删除行不删除的任何想法?

Any ideas why delete rows is not deleting?

推荐答案

因为您正在删除工作表顶部的行,所以您正在调整行索引.这意味着一旦您删除了一行,您要删除的所有其他行的索引都是错误的.为避免这种情况,您应该始终从工作表底部删除行.

Because you are deleting rows from the top of the worksheet you are adjusting row indices as you go. This means that as soon as you have deleted a single row, the indices for all the other rows you want to delete are wrong. To avoid this you should always delete rows from the bottom of the worksheet.

for r in reversed(del_rows):
    ws.delete_rows(r)

这篇关于无法让 OpenPyXl 删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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