[英]openpyxl - can not iterate over excel rows
I have a problem with iteration with openpyxl我在使用 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.我应该得到从 A1 到 B4 坐标的响应。 But instead I got only A1 to B1:
但相反,我只有 A1 到 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如果我用于sheet.iter_rows(min_row=1,max_row=4,min_col=1,max_col=2)中的行:而不是用于 sheet["A1":"B4"] 中的行,我得到了相同的结果
That means, I can not iterate through the 2., 3. and 4. rows这意味着,我无法遍历 2.、3. 和 4. 行
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您可以使用
sheet.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>)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.