簡體   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