1、增加EasyExcel的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>
2、创建excel数据对应的对象
@Data
public class Student implements Serializable{
/** 主键 */
@Id
//@GeneratedValue
private Long id ;
/** 账号;唯一 */
private String account ;
/** 密码;登陆密码 */
private String password ;
/** 姓名 */
private String name ;
}
3、excel中文件对应的数据
4、新建监听器
//使用EasyExcel进行学生信息的数据导入
public class StudentListener extends AnalysisEventListener<Student> {
private static final int BATCH_COUNT = 100;
private List<Student> list = new ArrayList<>();
private StudentBiz studentBiz;
public StudentListener(){
studentBiz = new StudentBiz();
}
public StudentListener(StudentBiz studentBiz){
this.studentBiz = studentBiz;
}
//读取数据的时候会执行invoke方法
@Override
public void invoke(Student student, AnalysisContext analysisContext) {
list.add(student);
// 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
if(list.size() >= BATCH_COUNT){
this.studentBiz.saveListStu(list);
list.clear(); //清空list
}
}
//所有的数据解析完成之后都会来调用
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
this.studentBiz.saveListStu(list); //确保最后遗留的数据保存在数据库中
}
}
5、编写接口controller层
此处有两种方法可以使用:
//数据的导入
@ApiOperation(value = "实现学生的数据导入")
@RequestMapping(value = "/importStuData",headers = "content-type=multipart/form-data")
public BaseResponse importStuData(MultipartFile multipartFile) throws Exception{
BaseResponse res = new BaseResponse();
String fileName = multipartFile.getOriginalFilename(); //获取文件名
String fileXlsx = fileName.substring(fileName.length()-5); //获取文件的后缀名为xlsx
String fileXls = fileName.substring(fileName.length()-4);
if(!(fileXlsx.equals(".xlsx") || fileXls.equals(".xls"))){ //如果不是excel文件
res.setStatus(400);
res.setMessage("文件格式错误");
return res;
}
// 方法一:
InputStream is = multipartFile.getInputStream();
EasyExcel.read(is,Student.class, new StudentListener(baseBiz)).sheet().doRead();
/*
// 方法二:
ExcelReader excelReader = null;
InputStream is = null;
try {
is = multipartFile.getInputStream();
excelReader = EasyExcel.read(is,Student.class,new StudentListener(baseBiz)).build();
ReadSheet readSheet = EasyExcel.readSheet(0).build();
excelReader.read(readSheet);
}catch (Exception e){
e.printStackTrace();
}finally {
is.close();
if(excelReader != null){
excelReader.finish();
}
}
*/
res.setMessage("数据导入成功");
return res;
}