""" author:少校 create Time:2025/2/25 15:44 越努力越幸运 """ import openpyxl # 练习1:写代码填写'员工信息'表中员工的出生日期信息 wb1 = openpyxl.load_workbook("files/员工信息.xlsx") yuanGong = wb1["员工信息"] mr = yuanGong.max_row for row in range(2,mr+1): ID = yuanGong.cell(row,4).value year = ID[6:10] month = ID[10:12] day = ID[12:14] value1 = f"{year}年{month}月{day}日" yuanGong.cell(row,6,value1) wb1.save("files/员工信息.xlsx") # 练习2: 创建一个新的excel文件保存下面班级中所有学生的信息 class1 = { 'name': 'python2501', 'address': '15教', '讲师': {'name': '余婷', 'age': 18, 'gender': '女', 'qq': '726550822'}, '班主任': {'name': '燕子姐', 'age': 18, 'tel': '120'}, 'students': [ {'name': 'stu1', 'age': 20, 'gender': '男', 'score': 98}, {'name': 'stu2', 'age': 22, 'gender': '女', 'score': 56}, {'name': 'stu3', 'age': 25, 'gender': '女', 'score': 87}, {'name': 'stu4', 'age': 19, 'gender': '男', 'score': 44}, {'name': 'stu5', 'age': 29, 'gender': '男', 'score': 76}, {'name': 'stu6', 'age': 16, 'gender': '女', 'score': 69} ] } wb2 = openpyxl.Workbook() if "学生信息" not in wb2.sheetnames: wb2.create_sheet("学生信息") xueSheng =wb2["学生信息"] stus = class1["students"] #先写入第一行数据 keys =list(stus[0].keys()) for x in range(len(keys)): value = keys[x] col = x +1 xueSheng.cell(1,col,value) #写入后面的学生信息 for x in range(len(stus)): stu = stus[x] row = x + 2 col = 0 for key in stu: col += 1 value = stu[key] xueSheng.cell(row,col,value) wb2.save("files/学生信息.xlsx") # 练习3:将销售数据文件中data表中拼多多的销售数据提取出来保存到'拼多多'表中。 # 1. 准备提供数据和保存数据的工作表 wb = openpyxl.load_workbook('files/2020年销售数据.xlsx') sheet1 = wb['data'] mr1 = sheet1.max_row mc1 = sheet1.max_column sheet2 = wb.create_sheet('拼多多') # 2. 获取原表中的数据,将满足条件的写入到新的表中 row2 = 0 for row1 in range(2, mr1+1): if row1 == 2 or sheet1.cell(row1, 3).value == '拼多多': row2 += 1 for col1 in range(1, mc1+1): value = sheet1.cell(row1, col1).value sheet2.cell(row2, col1, value) wb.save('files/2020年销售数据.xlsx')
05.实操练习
本节2631字2025-02-25 18:13:02