import xlwt

创建一个Workbook对象,用于保存Excel文件

workbook = xlwt.Workbook(encoding='utf-8')

添加一个sheet

sheet = workbook.add_sheet('学生信息')

初始化学生信息

students = [ {'序号': 1, '姓名': '张三', '学号': '1001', '成绩': None}, {'序号': 2, '姓名': '李四', '学号': '1002', '成绩': None}, {'序号': 3, '姓名': '王五', '学号': '1003', '成绩': None}, {'序号': 4, '姓名': '赵六', '学号': '1004', '成绩': None}, {'序号': 5, '姓名': '钱七', '学号': '1005', '成绩': None}, ]

定义一个函数,用于输出学生信息

def print_student_info(student): print('学号:{}, 姓名:{}'.format(student['学号'], student['姓名']))

定义一个函数,用于保存学生信息到Excel文件中

def save_to_excel(students): # 写入表头 sheet.write(0, 0, '序号') sheet.write(0, 1, '姓名') sheet.write(0, 2, '学号') sheet.write(0, 3, '成绩')

# 写入数据
for i, student in enumerate(students):
    sheet.write(i+1, 0, student['序号'])
    sheet.write(i+1, 1, student['姓名'])
    sheet.write(i+1, 2, student['学号'])
    sheet.write(i+1, 3, student['成绩'])

# 保存文件
workbook.save('学生成绩.xls')

输出所有学生信息

for student in students: print_student_info(student)

while True: # 输入学号或姓名 keyword = input('请输入学号或姓名:')

# 模糊匹配
matches = []
for student in students:
    if keyword in student['学号'] or keyword in student['姓名']:
        matches.append(student)

# 输出匹配结果
if len(matches) == 0:
    print('没有找到匹配的学生信息!')
elif len(matches) == 1:
    student = matches[0]
    print_student_info(student)
    # 输入成绩
    score = input('请输入成绩:')
    student['成绩'] = score
    # 保存到Excel文件中
    save_to_excel(students)
else:
    print('找到以下匹配的学生信息:')
    for student in matches:
        print_student_info(student)
    # 选择序号
    while True:
        choice = input('请选择序号(输入q退出):')
        if choice == 'q':
            break
        elif choice.isdigit() and int(choice) >= 1 and int(choice) <= len(matches):
            student = matches[int(choice)-1]
            print_student_info(student)
            # 输入成绩
            score = input('请输入成绩:')
            student['成绩'] = score
            # 保存到Excel文件中
            save_to_excel(students)

# 判断是否退出
if keyword == 'q':
    break

原文地址: https://www.cveoy.top/t/topic/nfKx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录