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']
.
Edit your sample to get what you want. But it's not recommended to do it this way!
Use one of the following samples:
Sampel1: Iter all columns per row, break after the first row.
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.
* Tested with Python:3.4.2 - openpyxl:2.4.1 *
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 theopenpyxl.worksheet.Worksheet.columns()
property.See Manipulating a workbook in memory.