问题
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