在第8节的基础之上,使用openpyxl根据某一列进行排序,数据地址:./basic/data/求一行数据的和.xlsx
有4列数据可以用来进行排序,语文,数学,英语,总分, 所以,应该实现一个函数,传入列的名称,表明以这一列进行排序。现在的学生成绩,写在一个明为“学生成绩”的sheet表中,排序后,可以选择仍然写在这个表中,也可以新建一个表,把排序后的数据写在新建的表中。
from openpyxl import load_workbook
file_path = './basic/data/求一行数据的和.xlsx'
workbook = load_workbook(file_path)
sheet = workbook.get_sheet_by_name('学生成绩')
row_lst = []
for row in sheet.rows:
row_data = [cell.value for cell in row]
row_lst.append(row_data)
print(row_lst) # 打印数据,进行观察
row_lst的数据内容为
[['姓名', '语文', '数学', '英语', '总分'],
['小刚', 98, 94, 96, 288],
['小明', 90.5, 98, 94, 282.5],
['小丽', 95.5, 100, 96, 291.5],
['小王', 97, 90, 95, 282]]
def sort_row_by_column_name(row_lst, name):
name_row = row_lst[0] # 第一行是各列的名称
index = name_row.index(name) # 获得列的索引
score_lst = row_lst[1:] # 用切片操作获得所有分数信息
score_lst = sorted(score_lst, key=lambda x: x[index], reverse=True) # 用指定列的值进行排序
score_lst.insert(0, name_row)
return score_lst
sort_name = '语文'
sort_row = sort_row_by_column_name(row_lst, sort_name)
pprint.pprint(sort_row)
sort_sheet = workbook.create_sheet(f"以{sort_name}排序") # 创建新的sheet
for row, lst in enumerate(sort_row):
for col, value in enumerate(lst):
sort_sheet.cell(row+1, col+1, value)
workbook.save(file_path)
将上面的代码进行整理
from openpyxl import load_workbook
def sort_by_column_name(filename, column_name):
#打开文件
workbook = load_workbook(filename)
sheet = workbook.get_sheet_by_name('学生成绩')
#读取数据
row_lst = []
for row in sheet.rows:
row_data = [cell.value for cell in row]
row_lst.append(row_data)
# 排序
sort_row = sort_row_by_column_name(row_lst, column_name)
sort_sheet = workbook.create_sheet(f"以{column_name}排序") # 创建新的sheet
for row, lst in enumerate(sort_row):
for col, value in enumerate(lst):
sort_sheet.cell(row + 1, col + 1, value)
workbook.save(filename)
def sort_row_by_column_name(row_lst, name):
name_row = row_lst[0] # 第一行是各列的名称
index = name_row.index(name) # 获得列的索引
score_lst = row_lst[1:] # 用切片操作获得所有分数信息
score_lst = sorted(score_lst, key=lambda x: x[index], reverse=True) # 用指定列的值进行排序
score_lst.insert(0, name_row)
return score_lst
if __name__ == '__main__':
file_path = './basic/data/求一行数据的和.xlsx'
column_name = "语文"
sort_by_column_name(file_path, column_name)
QQ交流群: 211426309