【问题标题】:Python loop through Excel rows using Openpyxl, updating cells based on a transaction IDPython 使用 Openpyxl 循环遍历 Excel 行,根据事务 ID 更新单元格
【发布时间】:2019-09-19 16:38:45
【问题描述】:

我正在尝试编写一个可以根据事务 ID 更新列的 scipt。我使用 Python3、Openpyxl 读取 excel 文件

在上图中,将在 K 列中用相同的值更新突出显示的单元格,因为它们在 C 列中具有相同的事务 ID。然后当它到达 C12 时,它用不同的值更新 K 列随着 C 的值发生变化......等等等等。

到目前为止我有:

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

更新

我尝试将 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

【问题讨论】:

  • 那么,你有什么问题呢?顺便提一句。这最好在数据库中完成。
  • @Charlie Clark 我无法让 while 循环根据需要写入 J 列。我使用 mysql 和 php 尝试过,处理 10000 行需要很长时间
  • 我想我可能会对那里的更新有所了解,我不知道你是否能清楚地看到我试图实现的内容
  • 我不知道您为什么要为此使用 PHP。如果您一次将所有内容加载到数据库中,则只需更新相关行。

标签: python excel openpyxl


【解决方案1】:

只是为了说明 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

但实际上应该在数据源中完成工作,大概是一个数据库。

【讨论】:

    猜你喜欢
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 2021-07-12
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多