繁体   English   中英

openpyxl遍历列=> TypeError的单元格:'generator'对象不可下标

[英]openpyxl iterate through cells of column => TypeError: 'generator' object is not subscriptable

我想遍历一列的所有值,以确保它们作为字典的键。 据我所知,一切都还可以,但是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

我一定很想念东西,但是经过几个小时的尝试,我必须扔下拖把并召唤骑兵;)

预先感谢所有帮助!

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

@查理·克拉克:感谢您抽出宝贵的时间回答。 事情是,我需要第一列作为字典中的键,之后,我需要做

for cell  in sheet.columns[1:]:

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

我主要遇到的问题是:

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

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

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

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

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

显然,在我不知情的情况下,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

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

x = sheet.max_row + 1

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM