首页 > 解决方案 > 使用 openpyxl 的数据修改 API

问题描述

假设我们有这个 Excel 表:

在此处输入图像描述

以下代码用于遍历所有行,并获取某些列的特定值,但它绝对不是很“pythonic”:

from openpyxl import load_workbook
wb = load_workbook('test.xlsx')
ws = wb.active

header = {col[0].value: i+1 for i, col in enumerate(ws.iter_cols())}  # mapping between column 
                                                                      # names (from header row) 
                                                                      # and their index
for i in range(2, ws.max_row+1):  # it would be interesting to not have to think about 2, max_row+1, etc.
    print(ws.cell(row=i, column=header['abc']).value)
    print(ws.cell(row=i, column=header['def']).value)
    # for example, print(ws[i, 'abc']) would be nicer (pandas-style)

问题:执行此操作的openpyxl内置方法是什么?

注意:我不想使用pandas它,因为我需要修改现有的 Excel 文件并保持布局/格式;另请参阅使用 Pandas 修改 Excel 文件,对布局进行最小的更改

第二个例子:假设我们想在column128中为columnabc 中的行523def设置一个值。我能找到的最好的是:

def find_row(ws, column, query):
    for i in range(2, ws.max_row+1):
        if ws.cell(row=i, column=column).value == query:
            return i
    return None

ws.cell(row=find_row(ws, header['def'], 523), column=header['abc'], value=128)

这可能不是最优的。

TL;DR:如何使用内置openpyxlAPI 执行此“查找行 + 替换值”?

标签: pythonexcelopenpyxlxlsx

解决方案


推荐阅读