You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
3.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""
Excel文件处理工具
"""
import pandas as pd
from typing import List, Dict, Tuple
from pathlib import Path
def read_students_from_excel(file_path: str) -> List[Dict]:
"""
从Excel文件读取学生信息
期望的Excel格式
- 第一行:表头(学号、姓名、专业)
- 后续行:学生数据
返回:学生信息列表
"""
try:
df = pd.read_excel(file_path)
# 标准化列名(支持多种可能的列名)
column_mapping = {
'学号': 'student_id',
'student_id': 'student_id',
'Student ID': 'student_id',
'姓名': 'name',
'name': 'name',
'Name': 'name',
'专业': 'major',
'major': 'major',
'Major': 'major'
}
# 重命名列
df.columns = df.columns.str.strip()
for old_name, new_name in column_mapping.items():
if old_name in df.columns:
df.rename(columns={old_name: new_name}, inplace=True)
# 检查必需列
if 'student_id' not in df.columns or 'name' not in df.columns:
raise ValueError("Excel文件必须包含'学号''姓名'")
# 转换为字典列表
students = []
for _, row in df.iterrows():
student = {
'student_id': str(row['student_id']).strip(),
'name': str(row['name']).strip(),
'major': str(row.get('major', '')).strip() if 'major' in df.columns else ''
}
# 过滤空行
if student['student_id'] and student['name']:
students.append(student)
return students
except Exception as e:
raise ValueError(f"读取Excel文件失败: {str(e)}")
def export_scores_to_excel(students_data: List[Dict], output_path: str) -> bool:
"""
导出积分详单到Excel文件
students_data: 包含学号、姓名、专业、随机点名次数、总积分的学生数据列表
output_path: 输出文件路径
"""
try:
df = pd.DataFrame(students_data)
# 确保列顺序
columns_order = ['学号', '姓名', '专业', '随机点名次数', '总积分']
df = df.reindex(columns=columns_order)
# 导出到Excel
df.to_excel(output_path, index=False, engine='openpyxl')
return True
except Exception as e:
raise ValueError(f"导出Excel文件失败: {str(e)}")
def create_template_excel(output_path: str) -> bool:
"""
创建Excel模板文件
"""
try:
template_data = {
'学号': ['2021001', '2021002', '2021003'],
'姓名': ['张三', '李四', '王五'],
'专业': ['软件工程', '计算机科学', '数据科学']
}
df = pd.DataFrame(template_data)
df.to_excel(output_path, index=False, engine='openpyxl')
return True
except Exception as e:
raise ValueError(f"创建模板文件失败: {str(e)}")