Openpyxl:似乎无法使我正在尝试做的语法正确(读下一个单元格)

时间:2016-06-11 16:29:01

标签: python excel openpyxl

这是我的代码。我只是试图打开一个电子表格(目前只有第一列中的信息),并读取第一个单元格,打印信息,然后沿着行循环返回到顶部并读取下一个单元格。我做错了什么?

import openpyxl

wb = openpyxl.load_workbook('students2.xlsx')

ws = wb.active

PrintNext = True #Starts my while statement
while True :

    for i in range(1,300):        #I think this is where I'm having an issue?
        for j in range(1,2):
            StudentID = ws.cell(row=i+1, column=j).value

    print(StudentID)
    PrintNext = False        #This gets it to move on from my while
    pass

PrintNext = True       #This is to get it to go back to my while
print(StudentID)       #This is to test that it has the next cell down

我在答案的帮助下找到了解决方案,但我找到了一个更好的解决方案。

将这些设置为变量:

for i in range(RowX,RowY):
    for j in range(ColX,ColY):
        StudentID = ws.cell(row=i+1, column=j).value

因此,您下次更新“for”语句时会反映您所做的任何更改(例如“RowX = RowX + 1”)!

1 个答案:

答案 0 :(得分:1)

您可以使用cell.offset()方法。