如何在 python 的 openpyxl 中更改/添加相同项目的值

问题描述 投票:0回答:2

我的数据Without modification.

代码:

for row in range(2, 6):
    result_cell = 'A{}'.format(row)
    column_a = ws[row("Quantity") + int(row)].value
    column_b = ws[row["Fruit"] +str(row)].value

    ws[result_cell] =  column_a + column_b

Expected

python python-3.x pandas dataframe openpyxl
2个回答
0
投票

如果我理解你的问题是正确的,你想要具有相同键的值的总和。为此,您可以使用字典,其中存储键第一次出现的行号。例如,在您的示例中,字典将类似于:

{"Apple": 2, "Banana": 3, "Orange":5}
。使用这个想法,代码将是这样的:

index_dict = {}
rows_to_delete = []
for row in range(2, sheet.max_row + 1):
    name = sheet.cell(row=row, column=1).value
    if name not in index_dict: # if it's the first time that this key (or name) has been seen
        index_dict[name] = row
    else: # if the key has been seen before
        sheet.cell(row=index_dict[name], column=2).value = (
            sheet.cell(row=index_dict[name], column=2).value
            + sheet.cell(row=row, column=2).value
        ) #  the value gets added to the first row with this key
        rows_to_delete.append(row) # add the row number with duplicated key

# delete the duplicated rows
for row in rows_to_delete:
    sheet.delete_rows(row)

workbook.save(file_path)

0
投票

这可以通过类似这样的循环来实现;
从底部开始并向上移动指针,随着指针的移动删除旧行。

import openpyxl

workbook = openpyxl.load_workbook('foo.xlsx')
sheet = workbook['Sheet1']

dict1 = {}
for row in reversed(range(2, sheet.max_row+1)):
    cell = sheet.cell(row=row, column=1)
    c_value = cell.value

    if c_value in dict1:
        old_row = dict1[c_value]
        for fruit, rownum in dict1.items():
            if rownum > old_row:
                dict1[fruit] = rownum-1
        cell.offset(column=1).value += sheet.cell(row=old_row, column=2).value
        sheet.delete_rows(old_row)
        dict1[c_value] = row
    else:
        dict1[c_value] = row

workbook.save("foo.xlsx")
© www.soinside.com 2019 - 2024. All rights reserved.