如何使用OpenPyXL列出Excel电子表格中的所有第一行值? [英] How can I list all 1st row values in an Excel spreadsheet using OpenPyXL?
问题描述
使用带有Python 3.5的OpenPyXL模块,我能够通过以下方式找出电子表格中有多少列:
Using the OpenPyXL module with Python 3.5, I was able to figure out how many columns there are in a spreadsheet with:
In [1]: sheet.max_column
Out [1]: 4
然后,我可以使用以下命令列出4个单元格中每个单元格的值:
Then I was able to list the values in each of the 4 cells with:
In [2]: for rowOfCellObjects in sheet['A1':'D1']:
for cellObj in rowOfCellObjects:
print(cellObj.coordinate, cellObj.value)
Out [2]: A1 Dog, B1 Cat, C1 Hamster, D1 Bigger Dog
但是有没有办法跳过第一步,只列出x
列数的值?
But is there a way to skip the first step and simply list the values for x
number of columns?
如果我不知道有多少列,我将不知道要遍历['A1':'D1]
.如果说有200列,那么计算['A1']
之后的第200个字母/数字将是浪费时间.
I wouldn't have known to iterate over ['A1':'D1]
if I didn't know how many columns there were. If there were say 200 columns it would be a time waster to calculate the 200th letter/number after ['A1']
.
推荐答案
编辑示例以获取所需的内容.但是不建议这样做!
Edit your sample to get what you want. But it's not recommended to do it this way!
for rowOfCellObjects in sheet['A1':sheet.cell(row=1, column=sheet.max_column).coordinate]:
for cellObj in rowOfCellObjects:
print(cellObj.coordinate, cellObj.value)
使用以下示例之一:
Sampel1:对每行的所有列进行迭代,在第一行之后中断.
Sampel1: Iter all columns per row, break after the first row.
for rows in ws.rows:
for cell in rows:
print('cell %s %s' % (cell.coordinate,cell.value))
break
更多程序控制:
Sample2:仅迭代由min/max_row参数指定的行中的所有列, 在一行之后结束.
Sample2: Iterates all columns only from the row given by min/max_row arguments, ends after one row.
参数min/max_row可以指向任何行,甚至可以指向外部数据.
Arguments min/max_row can point to any row, even also outside data.
for rows in ws.iter_rows(min_row=1, max_row=1, min_col=1):
for cell in rows:
print('cell %s %s' % (cell.coordinate,cell.value))
*使用Python:3.4.2测试-openpyxl:2.4.1 *
这篇关于如何使用OpenPyXL列出Excel电子表格中的所有第一行值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!