Python Openpyxl Insert row at each value change

2019-08-24 16:22发布

I am attempting to use Python to insert an empty row at each change, for instance:

Original Workbook:

A
A
A
B
B
C

Outcome:

A
A
A

B
B

C

Code I am working on:

    num=2
    while num < 13:
        if ws['A'+str(num)].value != ws['A'+str(num+1)].value:
            ws.insert_rows(num+1)
        elif ws['A'+str(num)].value == ws['A'+str(num+1)].value or ws['A'+str(num)].value == '':
            pass
        num+=1

Output I currently get is

A
A
A



B
B
C

Thanks in advance!

EDIT: SOLVED! In a weird way.

num=2
while num < 13:
    if ws['A'+str(num)].value == ws['A'+str(num+1)].value:
        pass
    elif ws['A'+str(num)].value == ws['J'+str(num)].value:
        pass
    elif ws['A'+str(num)].value != ws['A'+str(num+1)].value:
        ws.insert_rows(num+1)
    num+=1

1条回答
Luminary・发光体
2楼-- · 2019-08-24 17:13

How about to write the code a little bit more tidy. 1st read the input, then find the rows with differences, finally add the rows and save the wb:

from openpyxl import load_workbook

wb = load_workbook('example.xlsx')
ws = wb.active

values = [cell.value for cell in ws['A']]
diffs = [i for i in range(1, len(values)) if values[i] != values[i - 1]]
[ws.insert_rows(i+1) for i in reversed(diffs)]

wb.save('out.xlsx')
查看更多
登录 后发表回答