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;
}