【问题标题】:openpyxl iterate through cells of column => TypeError: 'generator' object is not subscriptableopenpyxl 遍历列的单元格 => TypeError: 'generator' object is not subscriptable
【发布时间】:2016-09-24 18:11:46
【问题描述】:

我想遍历列中的所有值,以将它们作为字典中的键来保护。据我所知,一切正常,但python不同意。

所以我的问题是:“我做错了什么?”

>>> wb = xl.load_workbook('/home/x/repos/network/input/y.xlsx')
>>> sheet = wb.active
>>> for cell  in sheet.columns[0]:
...     print(cell.value)
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'generator' object is not subscriptable

我一定是错过了什么,但经过几个小时的尝试,我必须放弃并召集骑兵;)

提前感谢所有帮助!

================================================ =====================

@Charlie Clark:感谢您花时间回答。问题是,我需要第一列作为字典中的键,然后,我需要做

for cell  in sheet.columns[1:]:

所以,虽然它可以解决我的问题,但它会在几行之后在我的代码中返回给我。我将在我的代码中使用您的建议来提取密钥。

我最关心的问题是:

为什么它不起作用,我确定我之前使用过这个代码 sn-p,这也是人们在谷歌搜索时建议这样做的方式。

================================================ =============================

>>> for column in ws.iter_cols(min_col = 2):
...     for cell in column:
...             print(cell.value)

遍历工作表的所有列,第一列除外。现在,我仍然需要排除前 3 行

【问题讨论】:

    标签: python excel loops openpyxl


    【解决方案1】:

    ws.columns 返回列的生成器,因为这在大型工作簿上效率更高,例如您的情况:您只需要一列。 Version 2.4 现在提供了直接获取列的选项:ws['A']

    【讨论】:

    【解决方案2】:

    显然,openpyxl 模块在我不知情的情况下升级到了 2.4。

    >>> for col in ws.iter_cols(min_col = 2, min_row=4):
    ...     for cell in col:
    ...         print(cell.value)
    

    应该可以解决问题。 我发布了这个以防其他人正在寻找相同的答案。

    iter_cols(min_col=None, max_col=None, min_row=None, max_row=None)[source]
    
    Returns all cells in the worksheet from the first row as columns.
    
    If no boundaries are passed in the cells will start at A1.
    
    If no cells are in the worksheet an empty tuple will be returned.
    Parameters: 
    
        min_col (int) – smallest column index (1-based index)
        min_row (int) – smallest row index (1-based index)
        max_col (int) – largest column index (1-based index)
        max_row (int) – smallest row index (1-based index)
    
    Return type:    
    
    generator
    

    【讨论】:

      【解决方案3】:

      我是新手,但我想出了以下基于openpyxl文档的代码来打印列的单元格内容:

      x = sheet.max_row + 1
      
      for r in range(1,x):
          d=sheet.cell(row=r,column=2)
          print(d.value)
      

      【讨论】:

        猜你喜欢
        • 2018-02-05
        • 1970-01-01
        • 1970-01-01
        • 2020-01-08
        • 2020-11-02
        • 1970-01-01
        • 2022-08-13
        • 1970-01-01
        • 2018-01-23
        相关资源
        最近更新 更多