I have a problem with iteration with openpyxl
wb = openpyxl.load_workbook(pfad,read_only=True)
sheet = wb.active
max_row = sheet.max_row
for row in sheet["A1":"B4"]:
print(row)
for cell in row:
print(cell.coordinate)
I should get the response of the coordinates from A1 to B4. But instead I got only A1 to B1:
(<ReadOnlyCell 'Tabelle1'.A1>, <ReadOnlyCell 'Tabelle1'.B1>)
A1
B1
If I used for row in sheet.iter_rows(min_row=1,max_row=4,min_col=1,max_col=2) : instead of for row in sheet["A1":"B4"] , I got the same result
That means, I can not iterate through the 2., 3. and 4. rows
I don´t know why it dosen´t work. Maybe I have ignored something? Thanks for any help!
======================== the problem is solved It is one part of a function and I inserted "return" the wrong way....
========================= in addition
the function looks like:
def excel_to_dict(pfad):
wb = openpyxl.load_workbook(pfad,read_only=True)
sheet = wb.active
list1 = []
max_row = sheet.max_row
print(max_row)
for row in sheet["A1":f"A{max_row}"]:
print(row)
for cell in row:
print(cell.coordinate)
c_value = cell.value
print(c_value)
list1.append(c_value)
return list1
see...? wrong indentaion bevor return so only the first row was returned.... I have changed the indentaion so everything is ok...
You can just use sheet.rows
to get all rows
>>> wb = openpyxl.load_workbook("excel.xlsx", read_only=True)
>>> sheet = wb.active
>>> rows = sheet.rows
>>> for row in rows:
... print(row)
...
(<ReadOnlyCell 'Sheet1'.A1>, <ReadOnlyCell 'Sheet1'.B1>)
(<ReadOnlyCell 'Sheet1'.A2>, <ReadOnlyCell 'Sheet1'.B2>)
(<ReadOnlyCell 'Sheet1'.A3>, <ReadOnlyCell 'Sheet1'.B3>)
(<ReadOnlyCell 'Sheet1'.A4>, <ReadOnlyCell 'Sheet1'.B4>)
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.