package com.example.classroomattendance.controller; import com.example.classroomattendance.model.Student; import com.example.classroomattendance.service.StudentService; import org.apache.poi.ss.usermodel.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; @Controller public class FileUploadController { @Autowired private StudentService studentService; @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file, Model model) { if (file.isEmpty()) { model.addAttribute("message", "文件为空"); return "index"; } try { List students = parseExcel(file); studentService.addStudents(students); model.addAttribute("message", "文件接收成功"); model.addAttribute("students", students); model.addAttribute("uploadSuccess", true); // 添加标志以显示下一步按钮 return "index"; // 返回 index 视图 } catch (IOException ex) { ex.printStackTrace(); model.addAttribute("message", "文件处理失败: " + ex.getMessage()); return "index"; } catch (Exception ex) { ex.printStackTrace(); model.addAttribute("message", "未知错误: " + ex.getMessage()); return "index"; } } private List parseExcel(MultipartFile file) throws IOException { List students = new ArrayList<>(); Workbook workbook = WorkbookFactory.create(file.getInputStream()); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { if (row.getRowNum() == 0) { continue; // 跳过标题行 } Cell nameCell = row.getCell(0); Cell studentIdCell = row.getCell(1); Cell pointsCell = row.getCell(2); if (nameCell == null || studentIdCell == null) { continue; // 跳过不完整的记录 } Student student = new Student(); student.setId((long) row.getRowNum()); // 使用行号作为 ID 示例 student.setName(getCellStringValue(nameCell)); student.setStudentId(getCellStringValue(studentIdCell)); student.setPoints(getCellDoubleValue(pointsCell)); students.add(student); } workbook.close(); return students; } private String getCellStringValue(Cell cell) { if (cell == null) { return ""; } switch (cell.getCellType()) { case STRING: return cell.getStringCellValue(); case NUMERIC: // 对于学号这种需要转换为字符串的情况,使用 DecimalFormat 保证不使用科学计数法 DecimalFormat df = new DecimalFormat("0"); return df.format(cell.getNumericCellValue()); default: return cell.toString(); } } private double getCellDoubleValue(Cell cell) { if (cell == null) { return 0.0; } switch (cell.getCellType()) { case NUMERIC: return cell.getNumericCellValue(); case STRING: try { return Double.parseDouble(cell.getStringCellValue()); } catch (NumberFormatException e) { return 0.0; } default: return 0.0; } } }