Python Openpyxl Insert row at each value change

纵然是瞬间 提交于 2019-12-13 03:27:04

问题


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:


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')


来源:https://stackoverflow.com/questions/57580054/python-openpyxl-insert-row-at-each-value-change

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