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
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
But is there a way to skip the first step and simply list the values for x
number of columns?
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']
.
If you need to iterate through all the rows or columns of a file, you can instead use the openpyxl.worksheet.Worksheet.rows()
property, or the openpyxl.worksheet.Worksheet.columns()
property.
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)
Use one of the following samples:
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
More programatical control:
Sample2: Iterates all columns only from the row given by min/max_row arguments, ends after one 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))
* Tested with Python:3.4.2 - openpyxl:2.4.1 *
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.