EasyExcel 入门
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.13</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.1</version>
</dependency>
下载/到出成excel
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@ExcelProperty("ID")
private Integer id;
@ExcelProperty("姓名")
private String name;
@ExcelProperty("余额")
private double money;
}
@GetMapping("download")
public void download(HttpServletResponse response) throws IOException {
//好像是固定写法
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition",
"attachment;filename=user_excel_" + System.currentTimeMillis() + "./xlsx" );
userService.download(response.getOutputStream());
}
public void download(ServletOutputStream outputStream) {
EasyExcelFactory.write(outputStream,User.class).sheet("User-sheet").doWrite(this::getUserList);
}
private Collection<?> getUserList() {
// 数据穿入
List<User> list = Collections.singletonList(User.builder().id(1).money(1.1).name("lf").build());
list.forEach(System.out::println);
return list;
}
上传
@PostMapping("/uploading")
public String uploading(@RequestParam(value = "file",required = true)MultipartFile file) throws IOException {
userService.upload(file.getInputStream());
return "ok";
}
private List<User> listUser = new ArrayList<>();
public void upload(InputStream inputStream) {
EasyExcelFactory.read(inputStream,User.class,new ReadListener<User>(){
@Override
public void invoke(User user, AnalysisContext analysisContext) {
listUser.add(user);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
listUser.forEach(user -> log.info(user.toString()));
}
}).sheet().doRead();
}