Python Openpyxl如何按索引从工作表中获取行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40561670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Openpyxl How to get row from worksheet by index
提问by Damilola Boiyelove
Using Openpyxl and python3.5, I tried getting the first row from an excel worksheet using a subscript but I an error.
使用 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
In relation to getting the first row, I've also tried first_row = worksheet.(row=1) # and first_row = worksheet.rows[:1]
关于获得第一行,我也试过 first_row = worksheet.(row=1) # 和 first_row = worksheet.rows[:1]
None worked. Any suggestions or is the feature not available in openpyxl? I've been to the documentation at https://openpyxl.readthedocs.io/en/default/but I found nothing helpful enough to index and select rows
没有一个工作。任何建议或该功能在 openpyxl 中不可用吗?我去过https://openpyxl.readthedocs.io/en/default/上的文档,但我发现没有足够的帮助来索引和选择行
回答by Damilola Boiyelove
I finally found the answer in the documentation:
我终于在文档中找到了答案:
first_row = worksheet[1]
# worksheet[row_index_from_1]
This worked for me.
这对我有用。
回答by Manuel Alvarez
The error TypeError: 'generator' object is not subscriptable
. Means that you are trying to access by index a generator, which doesn't have one, because it creates the elements as you iterate through it.
错误TypeError: 'generator' object is not subscriptable
。意味着您试图通过索引访问一个没有生成器的生成器,因为它会在您遍历它时创建元素。
You can solve it easily, cast it to a list to get the element you want:
您可以轻松解决它,将其转换为列表以获取您想要的元素:
first_row = list(worksheet.rows)[0]
or iterate thought the rows:
或迭代思考行:
for row in worksheet.rows:
foo(row)
This is because, even if both are iterables, lists and generators can behave quite differently, you can get it better explained here:
这是因为,即使两者都是可迭代对象,列表和生成器的行为也可能大不相同,您可以在此处更好地解释:
https://wiki.python.org/moin/Generators
https://wiki.python.org/moin/Generators
https://docs.python.org/3/library/stdtypes.html#iterator-types
https://docs.python.org/3/library/stdtypes.html#iterator-types
https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range
https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range