Openpyxl Version 2.4.5 TypeError: 'generator' object has no attribute '__getitem__'

Openpyxl Version 2.4.5 TypeError: 'generator' object has no attribute '__getitem__'

我正在 Automate the Boring Stuff 进行练习, 它使用 openpyxl 2.3.3 而我使用的版本是 2.4.5

我被困在这里:

import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.active
sheet.columns[1]

此时我遇到了这个错误:

>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.active
>>> sheet.columns[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'generator' object has no attribute '__getitem__'

这是因为我的命令有问题,还是因为我使用了不同的版本并且 sheet.columns 现在有不同的语法?

我用的excelsheet很简单,填了a1:c:7数据。 a 列是日期,b 列是字符串,c 列是整数。

谢谢

根据 the documentationsheet.columns 是工作表中各列的迭代器。

您可以将其转换为列表并索引:

columns = list(wb.active.columns)

或者如果您只想要那一列,您可以迭代它:

next(next(sheet.columns))

更新后的工作示例应该是:

import openpyxl

wb = openpyxl.load_workbook('example.xlsx')

sheet = wb.active

columnas = list(sheet)

for i in range(len(columnas)):
    print(columnas[i][0].value)