2017-03-05 66 views
0
import openpyxl 
wb = openpyxl.load_workbook('example.xlsx') 
sheet = wb.active 
sheet.columns[1] 
Traceback (most recent call last): 
    File "<pyshell#3>", line 1, in <module> 
    sheet.columns[1] 
TypeError: 'generator' object is not subscriptable 

我是Python初學者,這是我第一次發佈我的問題。 我堅持使用上面的TypeError說'發生器'對象不是可以訂閱的。我想我確切地輸入了寫在網站上的代碼。 該網站的網址是https://automatetheboringstuff.com/chapter12/TypeError:'發生器'對象不可自訂

請幫我解決這個錯誤。

+0

此代碼適用於我。正如@slai建議的那樣,檢查您的數據。 –

+0

不幸的是,這本書沒有被更新以反映API的變化。對於臨時訪問,使用Python的切片符號,例如。 'ws ['A']'獲得列A中的單元格列表。 –

回答

5

該教程是爲舊版本的openpyxl庫2.3.3設計的。從那時起,.columns的行爲已經發生了一些變化 - 我懶得查找什麼時候 - 現在它產生一個生成器,而不是(一個懶惰的對象,除非被要求,否則它實際上並沒有做任何工作)。

如果你不那麼在意性能,你可以調用list的發電機.columns回報,然後選擇合適的欄目:

>>> sheet.columns[0] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: 'generator' object is not subscriptable 
>>> list(sheet.columns)[0] 
(<Cell Sheet1.A1>, <Cell Sheet1.A2>, <Cell Sheet1.A3>, <Cell Sheet1.A4>, <Cell Sheet1.A5>, <Cell Sheet1.A6>, <Cell Sheet1.A7>) 
>>> list(sheet.columns)[1] 
(<Cell Sheet1.B1>, <Cell Sheet1.B2>, <Cell Sheet1.B3>, <Cell Sheet1.B4>, <Cell Sheet1.B5>, <Cell Sheet1.B6>, <Cell Sheet1.B7>) 

或按名稱選擇列:

>>> sheet["A"] 
(<Cell Sheet1.A1>, <Cell Sheet1.A2>, <Cell Sheet1.A3>, <Cell Sheet1.A4>, <Cell Sheet1.A5>, <Cell Sheet1.A6>, <Cell Sheet1.A7>) 

或 - 這可能是最簡單的,這取決於你想給可能遇到的其他問題多少時間 - 你可以降級到2.3.3。

+0

非常感謝您的回答。如果你不介意,請告訴我如何降級到2.3.3。老實說,我不知道關於openpyxl 2.3.3。 – User9712

+0

你是如何在第一個地方安裝openpyxl的?用點子?康達? – DSM

+0

對不起,我遲到的回覆。我用pip安裝了openpyxl。 – User9712

1

由於包的文檔中所述,由於版本2.4.0:

ws.rows and ws.columns now always return generators and start at the top of the worksheet

所以,如果你想獲得第1列,你可以(除了已經被DSM建議的方式)使用next()功能的發電機:

next(sheet.columns) 

但是,如果你仍然想降級openpyxl在本書中使用的版本,請嘗試:

pip install -I openpyxl==2.3.3 
相關問題