Skip to main content
 首页 » 编程设计

python之从 openpyxl 循环行获取单元格数据

2025年01月19日11EasonJim

我有一些代码可以在 Python 脚本中从 OpenPyXL 创建元组,如下所示:

for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50) 
    print(row) 

哪个返回

(<Cell 'States'.A2>, <Cell 'States'.B2>) 
(<Cell 'States'.A3>, <Cell 'States'.B3>) 
... 
(<Cell 'States'.A50>, <Cell 'States'.B50>) 

我想通过使用 cell.value 并进一步用逗号分隔值(例如 7,100 或 100, 7) 然后将值添加到字典中,如下所示:

StatesPriority = { 
    A2 : (B2.ValueBeforeComma, B2.ValueAfterComma) 
    A3 : (B3.ValueBeforeComma, B3.ValueAfterComma) 
    ... 
    A50 : (B50.ValueBeforeComma, B50.ValueAfterComma) 
} 

但是,我更关心从返回的元组中获取值的 OpenPyXL 函数。我想我可以花一点时间自己弄清楚用逗号拆分值。

Python 版本:3.6.3 OpenPyXL 版本:2.4.9

感谢所有帮助!

请您参考如下方法:

row 是一个包含两个元素的元组,因此您可以在赋值期间解压它:

StatesPriority = {} 
for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50) 
    cell_a, cell_b = row 
    StatesPriority[cell_a.value] = (tuple(cell_b.value.split(','))