首先 ,引入相关依赖EasyPOI
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
编写实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String username;
private String password;
private String email;
private Integer age;
private String phone;
private Integer isDeleted;
}
编写控制类UserController:
@RestController
public class UserController {
@SneakyThrows
@GetMapping("export")
public void exportExcel(HttpServletResponse response){
List<User> list = new ArrayList<>();
list.add(new User(1,"zhangsan","aaa","28181@163.com",18,"13256564454",1));
list.add(new User(2,"lisi","aaa","28181@163.com",28,"18456234454",0));
list.add(new User(3,"Wangwu","aaa","28181@163.com",38,"18423564454",1));
list.add(new User(4,"mazi","aaa","28181@163.com",15,"18456564454",1));
// 传入表头和表名
ExportParams exportParams = new ExportParams("员工信息表","员工表");
Workbook sheets = ExcelExportUtil.exportExcel(exportParams,User.class,list);
//设置响应输出的类型为excel
response.setContentType("application/vnd.ms-excel");
//设置相应的文件名
String filename = UUID.randomUUID() + ".xlsx";
response.setHeader("Content-disposition","attachment;filename="+ new String(filename.getBytes("utf-8"),"iso8859-1"));
sheets.write(response.getOutputStream());
}
}
实现导出元素:
现在进行导入操作:
@SneakyThrows
@PostMapping("import")
public AjaxResult importExcel(@RequestParam(value = "file") MultipartFile file){
ImportParams params = new ImportParams();
params.setTitleRows(1);// 标题行数
params.setHeadRows(1); // 列名行数
List<User> list = ExcelImportUtil.importExcel(file.getInputStream(), User.class, params);
list.forEach(System.out::println);
return success();
}
使用postman进行导入测试:
导入的表格元素入下所示:
控制台打印结果: