如何获取用户输入以在 openpyxl 中显示单元格数据?

How to get user input to display cell data in openpyxl?

我正在尝试让 Python 使用 openpyxl 读取 Excel 文件。我需要让用户输入学号,Python 将 return 学生姓名。我卡住了。

非常感谢任何帮助!

到目前为止,我只得到 Not found

import openpyxl
roster = openpyxl.load_workbook('sample.xlsx')
sheet = roster.active

st_id = int(input("Enter student ID: "))

col3 = sheet['C']
for cell in col3:
    if cell.value == st_id:
        print(cell)
    else:
        print('Not found.')

sample.xlsx

您最好遍历 Excel 文件中的所有行。你可以这样做:

    for row in sheet.rows:
        if row[2].value == st_id:
            print("First Name: {}\tLast Name: {}".format(row[0].value, row[1].value))
        else:
            print('Not found.')

这将打印 table 中任何其他行的输入学生信息和 Not found.,与您的原始实现相同。 如果您只想在 Excel 文件中的输入 ID 而不是 时打印 Not found.,您可以像这样使用 for-else

  for row in sheet.rows:
        if row[2].value == st_id:
            print("First Name: {}\tLast Name: {}".format(row[0].value, row[1].value))
            break
  else: # note the indentation
      print('Not found.')

请注意row 是一个 tuple 在你的情况下有三列,我最好使用一些更通用的方法来访问 tuple 的每个部分 :-)