【问题标题】:Python 3 - openpyxl - Iterating through column by namePython 3 - openpyxl - 按名称迭代列
【发布时间】:2016-01-11 21:42:18
【问题描述】:

使用openpyxl不是按数字而是按列标题(ws第一行中的字符串值)遍历列的最简单方法是什么:

类似这样的:

for cell in ws.columns['revenue']:
    print(cell.value)

【问题讨论】:

    标签: python excel openpyxl


    【解决方案1】:

    列标题不存在,因此您必须根据第一行中的名称创建一些内容来表示它们:

    headers = {}
    for idx, cell in enumerate(ws.iter_rows(min_row=1, max_row=1), start=1):
        headers[cell.value] = idx
    
    revenue = ws.columns[headers['revenue']]
    

    ws.columns 将返回 all 列,这在大型工作表上可能会很慢。

    您还可以添加一个命名范围来表示相关单元格并循环访问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 2018-04-29
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      相关资源
      最近更新 更多