gpt4 book ai didi

python - 使用 xlrd 按列名获取单元格

转载 作者:行者123 更新时间:2023-11-28 17:52:32 28 4
gpt4 key购买 nike

如果我在 Excel (.xls) 工作表中有两行,如键值对,是否可以通过在 xlrd 中输入键(行 0)来获取值(行 1)?

例如,如果我有 (0,0) = COLOR(1,0) = RED,我会怎么做:

value = sh.col_values("COLOR") ?

我能找到的最接近的是 sh.col_values(int),但它只允许我输入索引。

最佳答案

您必须向下搜索该列,直到找到 COLOR,然后在下一行中获取值。

from itertools import product

def value_from_key(sheet, key):
for row_index, col_index in product(xrange(sheet.nrows), xrange(sheet.ncols)):
if sheet.cell(row_index, col_index).value == key:
return sheet.cell(row_index+1, col_index).value

value = value_from_key(sheet, 'COLOR')

如果您知道键在偶数行或奇数行中,您可以使用 xrange(0, sheet.nrows, 2)xrange(1, sheet.nrows, 2) 代替。

编辑:也更新为搜索列。

关于python - 使用 xlrd 按列名获取单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6970543/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com