目录
一、依赖添加
- 两个主要依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.21</version>
</dependency>
二、实体类
- 创建一个Student实体类
@Data
@TableName("excel")
public class Student implements Serializable {
@ExcelProperty(value = "id")
private Integer id;
@ExcelProperty(value = "姓名")
private String name;
@ExcelProperty(value = "性别")
private String gender;
@ExcelProperty(value = "身份证号")
private Integer code;
@ExcelProperty(value = "生日",format = "yyyy-MM-dd")
private Date birthday;
@ExcelProperty(value = "录入时间",format = "yyyy-MM-dd")
private Date createTime;
}
三、监听器
- // 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去需要手动写入一个有参构造方法
package org.example.utils;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.Student;
import org.example.service.StuService;
import java.util.List;
@Slf4j
public class StuExcelListener implements ReadListener<Student> {
/**
* 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 100;
/**
* 缓存的数据
*/
private List<Student> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
private StuService stuService;
/**
* 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
*
* @param
*/
public StuExcelListener(StuService stuService) {
this.stuService = stuService;
}
@Override
public void invoke(Student data, AnalysisContext analysisContext) {
log.info("解析到一条数据:{}", JSON.toJSONString(data));
cachedDataList.add(data);
// 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
// 存储完成清理 list
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
// 这里也要保存数据,确保最后遗留的数据也存储到数据库
saveData();
log.info("所有数据解析完成!");
}
private void saveData() {
log.info("{}条数据,开始存储数据库!", cachedDataList.size());
stuService.batchImportStuInfo(cachedDataList);
log.info("存储数据库成功!");
}
}
四、mapper层
package org.example.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.example.entity.Student;
import java.util.List;
@Mapper
public interface StuMapper extends BaseMapper<Student> {
// 批量导入学生信息
Integer batchImportStuInfo(List<Student> studentList);
List<Student> readForDataSource();
}
五、service层
package org.example.service;
import org.example.entity.Student;
import java.util.List;
public interface StuService {
//批量导入
public Integer batchImportStuInfo(List<Student> list);
//导出excel文件
public void downloadFileByEasyExcel();
}
实现类
package org.example.service.impl;
import com.alibaba.excel.EasyExcel;
import org.example.entity.Student;
import org.example.mapper.StuMapper;
import org.example.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StuServiceImpl implements StuService {
@Autowired
private StuMapper mapper;
@Override
public Integer batchImportStuInfo(List<Student> list) {
return mapper.batchImportStuInfo(list);
}
@Override
public void downloadFileByEasyExcel() {
List<Student> stuList = mapper.readForDataSource();
EasyExcel.write("C:\\Users\\Administrator\\Desktop\\easyExcel.xls", Student.class)
.sheet()
.doWrite(stuList);
}
}
六、controller层
package org.example.controller;
import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.Student;
import org.example.service.StuService;
import org.example.utils.StuExcelListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@Slf4j
@RestController
@Api(tags = "excel功能模块")
@RequestMapping("/upload")
public class StuController {
@Autowired
private StuService stuService;
/**
* excel文件上传
* @param file
* @return
*/
@ApiOperation("excel文件上传")
@PostMapping("/uploadExcel")
public String uploadFileByEasyExcel(@RequestParam("file") MultipartFile file) {
try {
EasyExcel.read(file.getInputStream(), Student.class, new StuExcelListener(stuService)).sheet().doRead();
return "文件上传成功";
} catch (IOException e) {
log.error("error msg 【{}】", e);
throw new IllegalArgumentException(e);
}
}
/**
* excel文件导出
*/
@ApiOperation("excel文件导出")
@GetMapping("/downloadExcel")
public String downloadFileByEasyExcel() {
stuService.downloadFileByEasyExcel();
return "文件下载成功!";
}
}
七、测试
测试数据:
excel文件
mysql:
使用knife4j进行测试
导入: