我有两个 Excel 文件需要对齐,因为一个 excel 文件中的每一行在另一个 excel 文件中都有一个唯一的对应行,它是匹配的数据点或空白值。Excel 文件的大小不同,并且有一些匹配的值和一些不匹配的值,但是它们都是按顺序排列的。
我试图通过插入空行来实现这一点。当没有匹配然后继续下一个值时,我无法插入正确数量的空行。我相信我的代码非常接近工作。代码中还包含两个修改过的 Excel 文件作为单独的选项卡合并到一个文件中。
j=0
iterations=100+Branch_Flow_Pre.max_row
for i in range(2, iterations):
#if str(Branch_Flow_Pre.cell(row=i, column=1).value) == "None" and str(Branch_Flow_Post.cell(row=i, column=1).value) == "None":
# print("blanks, i = ",i,"j = ",j)
# i += 1
if Branch_Flow_Pre.cell(row=i, column=2).value == Branch_Flow_Post.cell(row=i, column=2).value and Branch_Flow_Pre.cell(row=i, column=8).value == Branch_Flow_Post.cell(row=i, column=8).value:
print("match, i = ",i,"j= ",j)
i += 1
else:
j=0
while j<21:
if Branch_Flow_Pre.cell(row=i+j, column=2).value == Branch_Flow_Post.cell(row=i, column=2).value and Branch_Flow_Pre.cell(row=i+j, column=8).value == Branch_Flow_Post.cell(row=i, column=8).value:
if j!=0:
for x in range(0, j+1):
Branch_Flow_Post.insert_rows(i)
print("insert Post, x = ",x,"i = ",i,"j = ",j)
else:
print("error")
i = i+j
j=21
break
elif Branch_Flow_Pre.cell(row=i, column=2).value == Branch_Flow_Post.cell(row=i+j, column=2).value and Branch_Flow_Pre.cell(row=i, column=8).value == Branch_Flow_Post.cell(row=i+j, column=8).value:
if j!=0:
for x in range(0, j+1):
Branch_Flow_Pre.insert_rows(i)
print("insert Pre, x = ",x,"i = ",i,"j = ",j)
else:
print("error")
i = i+j
j=21
break
elif j==20:
Branch_Flow_Post.insert_rows(i)
print("break, i = ",i,"j = ",j," Insert Post")
i += 1
j = 21
break
else:
print("increment, i = ",i,"j = ",j)
j += 1
c=1
r=2
for row in Branch_Flow_Pre.values:
for v in row:
BF_Pre.cell(row=r, column=c).value = v
c += 1
c=1
r += 1
c=1
r=2
for row in Branch_Flow_Post.values:
for v in row:
BF_Post.cell(row=r, column=c).value = v
c += 1
c=1
r += 1
book3.save(outfilename)
## the rest is not code
desired output:
Input1 Input2 Output1 Output2
A 1 B 2 A 1
B 2 B 2 B 2
C 3 C 3
x y C 3 C 3
D 4 x y
D 4
D 4 D 4
Actual output:
Input1 Input2 Output1 Output2
A 1 B 2 A 1
B 2 B 2 B 2
C 3 C 3
x y C 3
D 4
D 4
D 4
C 3
x y
D 4