本文介绍了Python Openpyxl在每个值更改时插入行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Python在每次更改时插入一个空行,例如:
I am attempting to use Python to insert an empty row at each change, for instance:
原始工作簿:
A
A
A
B
B
C
结果:
A
A
A
B
B
C
我正在处理的代码:
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
我当前得到的输出是
A
A
A
B
B
C
提前谢谢!
已解决!以一种奇怪的方式.
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
推荐答案
如何编写更加整洁的代码.首先读取输入,然后找到有差异的行,最后添加行并保存wb:
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')
这篇关于Python Openpyxl在每个值更改时插入行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!