pom.xml添加导入导出依赖
<!-- 导入导出 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.19</version>
</dependency>
Controller控制层
导入:
@PostMapping("/importExcel")
public int importExcel(@RequestParam MultipartFile file) throws IOException {
ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
List<List<Object>> lists = reader.read();
int count=0;
for (List<Object> obj:lists) {
Integer stuId = Integer.valueOf(String.valueOf(obj.get(0)+""));//Integer转String
// BigDecimal price = BigDecimal.valueOf(Long.parseLong(obj.get(3)+""));//BigDecimal转String
// BigDecimal totalprice = BigDecimal.valueOf(Long.parseLong(obj.get(5)+""));
Student student=new Student(stuId,obj.get(1)+"",obj.get(2)+"",obj.get(3)+"",obj.get(4)+"",obj.get(5)+"");
count += studentService.addStudent(student);
}
return count;
}
导出:
@GetMapping("/exportExcel")
public void exportExcel(@RequestParam(required = false,defaultValue = "") Integer stuId,
@RequestParam(required = false,defaultValue = "") String stuname,
@RequestParam(required = false,defaultValue = "") String gender,
@RequestParam(required = false,defaultValue = "") String major,
@RequestParam(required = false,defaultValue = "") String classes,
@RequestParam(required = false,defaultValue = "") String phoneId,
HttpServletRequest request, HttpServletResponse response) throws IOException {
//Excel写入器
ExcelWriter writer = ExcelUtil.getWriter();
//获取所有学生信息
Student student = new Student();
student.setStuId(stuId);
student.setStuname(stuname);
student.setGender(gender);
student.setMajor(major);
student.setClasses(classes);
student.setPhoneId(phoneId);
// if(!birthday.equals("")){
// student.setBirthday(DateUtil.parse(birthday,"yyyy-MM-dd"));
// }
List<Student> allDitys = studentService.getStudent(student);
//写入
writer.write(allDitys,true);
//当前响应对象输出流
ServletOutputStream outputStream = response.getOutputStream();
//设置Http响应的内容为Excel类型
response.setContentType("application/vnd.ms-excel;charset=utf-8");
//添加附件
response.setHeader("Content-Disposition","attachment;filename="+ UUID.randomUUID()+".xls");
//将Excel输出到响应流中
writer.flush(outputStream,true);
//关闭
writer.close();
IoUtil.close(outputStream);
}