Can't get OpenPyXl to delete rows

混江龙づ霸主 提交于 2019-12-13 21:16:08

问题


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?

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?


回答1:


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)



来源:https://stackoverflow.com/questions/53376617/cant-get-openpyxl-to-delete-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!