[英]Python loop through Excel rows using Openpyxl, updating cells based on a transaction ID
I'm trying to write a scipt that can update a column based on a transaction ID. 我正在尝试编写一个可以根据事务ID更新列的scipt。 Im using Python3, Openpyxl to read the excel file
我正在使用Python3,Openpyxl读取Excel文件
In the above image, it would be to update the highlighted cells with the same value in column K, as they have the same transaction ID in column C. Then when it gets to C12, it updates column K with a different value as the value of C has changed...and so on and so on. 在上图中,将用K列中具有相同值的突出显示的单元格来更新,因为它们在C列中具有相同的事务ID。然后,当到达C12时,它将使用与该值不同的值来更新K列。 C的值已更改...等等。
So far I have: 到目前为止,我有:
from openpyxl import load_workbook, Workbook
import re
wb = load_workbook(filename = 'Testing.xlsx')
ws = wb['Test']
for r in range(2, ws.max_row + 1):
column_c = ws.cell(row = r, column = 3).value
column_h = ws.cell(row = r, column = 8).value
column_i = ws.cell(row = r, column = 9).value
column_j = ws.cell(row = r, column = 10).value
previous = None
while (previous == column_c):
ws.cell(row = r, column = 11).value = column_j_formatted
if (previous != column_c):
continue
wb.save('Testing_processed.xlsx')
UPDATE 更新
I have tried to replace the while loop with: 我试图用以下方式替换while循环:
previous_col_c = ws.cell(row=r-1, column=3)
for row_num in range (2, ws.max_row + 1):
current_col_c = ws.cell(row=r, column=3)
current_col_j = ws.cell(row=r, column=11)
if current_col_c == previous_col_c:
ws.cell(row = r, column = 11).value = column_j_formatted
previous_col_c = current_col_c
Just to illustrate how the openpyxl API makes this kind of task very easy. 只是为了说明openpyxl API如何使这种任务非常容易。
txn = None
filler = None
for row in ws.iter_rows(min_row=2):
a = row[0]
k = row[10]
if a.value != txn:
txn = a.value
filler = k.value
if not k.value:
k.value = filler
But really the work should be done in the source of the data, presumably a database. 但是实际上应该在数据源(大概是数据库)中完成工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.