簡體   English   中英

Openpyxl如何通過索引從工作表中獲取行

[英]Openpyxl How to get row from worksheet by index

使用Openpyxl和python3.5,我嘗試使用下標從excel工作表中獲取第一行,但我是一個錯誤。

# after getting filename
# after loading worksheet
# to get the first row of the worksheet
first_row = worksheet.rows[0]

# I get 
Traceback (most recent call last):
      File "<pyshell#54>", line 1, in <module>
      first_row = phc_th_sheet.rows[1]
TypeError: 'generator' object is not subscriptable

關於獲取第一行,我也嘗試過first_row =工作表。(row = 1)#和first_row = worksheet.rows [:1]

沒有用。 任何建議或openpyxl中沒有的功能? 我去過https://openpyxl.readthedocs.io/en/default/上的文檔,但我發現沒有什么有用的索引和選擇行

我終於在文檔中找到了答案:

first_row = worksheet[1]
# worksheet[row_index_from_1]

這對我有用。

錯誤TypeError: 'generator' object is not subscriptable 意味着您嘗試通過索引來訪問沒有索引的生成器,因為它會在您遍歷它時創建元素。

您可以輕松地解決它,將其轉換為列表以獲得您想要的元素:

first_row = list(worksheet.rows)[0]

或迭代思考行:

for row in worksheet.rows:
    foo(row)

這是因為,即使兩者都是迭代,列表和生成器的行為也可能完全不同,您可以在此處更好地解釋:

https://wiki.python.org/moin/Generators

https://docs.python.org/3/library/stdtypes.html#iterator-types

https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM