使用Apache POI结合Spring Boot实现学生信息批量导入导出,支持Excel文件读写、数据校验与数据库交互。1. 导入功能通过XSSFWorkbook解析上传的Excel文件,逐行读取学生信息并封装为Student对象列表;2. 数据校验包括字段非空、学号唯一性、年龄范围及性别合法性检查;3. 校验通过后调用JPA的saveAll方法批量持久化到MySQL数据库;4. 导出功能查询全部学生数据,创建Excel工作簿并填充表头与数据行;5. 设置响应头使浏览器触发文件下载。需注意空行处理、异常捕获及用户反馈,提升系统健壮性与体验。

在Java项目中实现学生信息的批量导入与导出功能,通常涉及Excel文件操作,结合后端业务逻辑处理数据。常见的技术组合包括Apache POI、Spring Boot、MySQL等。下面从需求分析到代码实现,说明具体开发方法。
功能需求与技术选型
学生信息批量导入导出主要用于教务系统或管理系统中,提升数据录入效率。核心功能包括:
- 支持上传Excel文件(.xls 或 .xlsx)导入学生信息
- 将数据库中的学生数据导出为Excel文件
- 数据校验(如学号重复、字段为空等)
- 异常处理与用户提示
推荐技术栈:
使用Apache POI实现Excel读写
Apache POI是Java操作Office文档的核心库,支持读写Excel。
立即学习“Java免费学习笔记(深入)”;
添加Maven依赖:
读取Excel(导入)示例:
public ListimportStudents(MultipartFile file) throws IOException { List students = new ArrayList<>(); Workbook workbook = new XSSFWorkbook(file.getInputStream()); Sheet sheet = workbook.getSheetAt(0); for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); if (row != null) { Student student = new Student(); student.setStudentId(row.getCell(0).getStringCellValue()); student.setName(row.getCell(1).getStringCellValue()); student.setAge((int) row.getCell(2).getNumericCellValue()); student.setGender(row.getCell(3).getStringCellValue()); students.add(student); } } workbook.close(); return students; }
注意:需对空行、数据类型、格式做判断,避免运行时异常。
数据校验与数据库操作
导入前应对数据进行合法性检查,防止脏数据进入系统。
- 检查必填字段是否为空
- 验证学号唯一性(查询数据库)
- 年龄应在合理范围(如 10-100)
- 性别只能是“男”或“女”
校验通过后,使用JPA或MyBatis批量插入:
@Transactional public void saveAll(Liststudents) { studentRepository.saveAll(students); // JPA方式 }
若部分数据出错,可返回错误明细给前端,提示用户修正Excel重新上传。
导出学生信息到Excel
将数据库中的学生列表导出为Excel文件供下载。
public void exportStudents(HttpServletResponse response) throws IOException {
List students = studentRepository.findAll();
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("学生信息");
// 创建表头
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("学号");
header.createCell(1).setCellValue("姓名");
header.createCell(2).setCellValue("年龄");
header.createCell(3).setCellValue("性别");
// 填充数据
int rowNum = 1;
for (Student s : students) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(s.getStudentId());
row.createCell(1).setCellValue(s.getName());
row.createCell(2).setCellValue(s.getAge());
row.createCell(3).setCellValue(s.getGender());
}
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=students.xlsx");
workbook.write(response.getOutputStream());
workbook.close();
}
前端可通过一个按钮发起GET请求触发下载。
基本上就这些。导入导出功能看似简单,但关键在于数据安全和用户体验。做好异常捕获、进度提示和错误反馈,才能让功能真正可用。实际项目中还可加入异步处理、模板下载、日志记录等增强功能。










