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

jbose2ul  于 2023-05-08  发布在  Python
关注(0)|答案(2)|浏览(124)

我有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

ppcbkaq5

ppcbkaq51#

这可以通过类似的一个循环来实现;
从底部开始,向上移动指针,将值添加到下一个有效行,然后在指针移动时删除旧行。

import openpyxl

wb = openpyxl.load_workbook('foo.xlsx')
ws = wb['Sheet1']

rpointer = {}
### Reverse loop start at max row 
for row in reversed(range(2, ws.max_row+1)): 
    cell = ws.cell(row=row, column=1)
    c_value = cell.value

    if c_value in rpointer:  # Check if fruit already has a pointer
        old_row = rpointer[c_value]  # last row to hold this fruit 

        ### Update fruit row pointers if row deletion will move them up 
        for fruit, rownum in rpointer.items(): 
            rpointer[fruit] = rownum-1 if rownum > old_row else rownum

        ### Add the value in old fruit row to value of new fruit row    
        cell.offset(column=1).value += cell.offset(row=old_row-row, column=1).value

        ### Delete the old fruit row
        ws.delete_rows(old_row)

    ### Set row pointer for a new or current fruit 
    rpointer[c_value] = row

wb.save("foo1.xlsx")
vh0rcniy

vh0rcniy2#

如果我理解你的问题是正确的,你想要的是具有相同键的值的总和。为此,您可以使用字典,在其中存储键第一次出现的行号。例如,在你的例子中,字典应该是这样的:{"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[::-1]:
    sheet.delete_rows(row)

workbook.save(file_path)

相关问题