其实就是字典的应用,把其中一个表格做成字典(将需要查询的元素设为字典的键),然后读取另一个表格逐个在字典中查找
表1:
表2:
import openpyxlwb1 = openpyxl.load_workbook(r"C:\Users\Lenovo\Desktop\表1.xlsx") ws1 = wb1["Sheet1"] wb2 = openpyxl.load_workbook(r"C:\Users\Lenovo\Desktop\表2.xlsx") ws2 = wb2["Sheet1"]dict = {} for row in ws1.iter_rows(min_row = 2,values_only=True):#按行遍历 ,第2行开始dict[row[0]]=[row[0],row[1],row[2],row[3],row[4]] #字典 {'张三': ['张三', '男', 202501, 21, 1], '李四': ['李四', '男', 202502, 22, 2], '王五': ['王五', '女', 202503, 23, 3], '赵六': ['赵六', '女', 202504, 24, 4]} num = 1 for row in ws2.iter_rows(min_row = 2,values_only=True):#按行遍历num += 1 #行号if row[0] in dict:#如果需要查询的元素在字典中(将需要查询的元素设为字典的键)print(num,row[0],row[1],row[2],row[3],row[4]) #行号 姓名 性别 学号 年纪 班级
结果: