Can't get OpenPyXl to delete rows

2019-08-29 05:53发布

问题:

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)