1. 创建项目,导入easy excel的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
2. 配值application.yml文件
server:
port: 8081
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/portdemo?serverTimezone=UTC&characterEncoding=utf-8
username: root
password: 123456
application:
name: demoExport
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3.创建数据库表实体
@Data
@TableName("sys_user")
@ContentRowHeight(18)
@HeadRowHeight(25)
@ColumnWidth(20)
public class User {
@ExcelProperty(index = 0, value = "申请人ID")
private Integer userId;
@ExcelProperty(index = 1, value = "申请人姓名")
private String userName;
@ExcelProperty(index = 2, value = "申请人身份证号")
private String userCard;
@ExcelProperty(index = 3, value = "申请人班级")
private String userClass;
@ExcelProperty(index = 4, value = "申请人邮箱")
private String userMail;
}
4. 业务逻辑
4.1 导出excel
@GetMapping("downLoad")
public void downLoad(HttpServletResponse response) throws IOException {
List<User> users = exportService.list();
exportService.downLoad(response, users);
}
@Override
public void downLoad(HttpServletResponse response, List<User> users) throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
String fileName = URLEncoder.encode("userExcel", "UTF-8").replaceAll("\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), User.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet("学生记录").build();
excelWriter.write(users, writeSheet);
excelWriter.finish();
}
4.2 导入excel
@PostMapping("upload")
public String upload(@RequestPart("file")MultipartFile file) throws IOException {
exportService.upload(file);
return "success";
}
@Override
public void upload(MultipartFile file) throws IOException {
ExcelReader reader = EasyExcel.read(file.getInputStream(), User.class,
new ExportListener(exportMapper)).build();
ReadSheet sheet = EasyExcel.readSheet(0).build();
reader.read(sheet);
reader.finish();
}
4.3 工具类 `ExportListener
@Slf4j
public class ExportListener extends AnalysisEventListener<User> {
private static final int BATCH_COUNT = 100;
private List<User> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
private ExportMapper exportMapper;
public ExportListener(ExportMapper exportMapper) {
this.exportMapper = exportMapper;
}
@Override
public void invoke(User user, AnalysisContext context) {
log.info("解析到一条数据:{}", JSON.toJSONString(user));
user.setUserId(null);
cachedDataList.add(user);
if (cachedDataList.size() >= BATCH_COUNT) {
exportMapper.insert(user);
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
log.info("所有数据解析完成,进入doAfterAllAnalysed方法");
}
private void saveData() {
log.info("{}条数据,开始存储数据库...", cachedDataList.size());
for (User user : cachedDataList) {
exportMapper.insert(user);
}
log.info("存储数据完成!!");
}
}