EasyExcelFactory 导入导出功能的实战使用分享:
1、jar包引入
<!-- 阿里巴巴Excel处理--><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.0.6</version></dependency>
2、excel文档准备
注意:首行名称要和后面实体类里注解的名称保持一样,否则失效。
3、实体类
@Data
@HeadRowHeight(20)
@ColumnWidth(20)
public class DemoData {@ExcelProperty("id")private Long id;@ExcelProperty("name")private String name;@ExcelProperty("model")private String model;@ExcelProperty("tail")private String tail;}
4、控制层接口样例
@PostMapping("/import/userBox")public ResponseResult<Boolean> importUserBox(@RequestParam("file") MultipartFile file,@RequestParam("start") Integer start,@RequestParam(value = "sheetNo", required = false, defaultValue = "0") Integer sheetNo) {try {UserBoxConfigListener listener = new UserBoxConfigListener();EasyExcelFactory.read(file.getInputStream(), UserBoxConfigBo.class, listener).sheet(sheetNo).headRowNumber(start);List<UserBoxConfigAddReq> list = listener.getList();return ResponseResult.success(userBoxConfigService.batchAdd(list));} catch (Exception e) {e.printStackTrace();return ResponseResult.error(e.getMessage());}}
5、监听类继承
@Slf4j
public class UserBoxConfigListener extends AnalysisEventListener<UserBoxConfigBo> {private List<UserBoxConfigAddReq> list;public UserBoxConfigListener() {list = new ArrayList<>();}@Overridepublic void invoke(UserBoxConfigBo data, AnalysisContext context) {UserBoxConfigAddReq item = BeanUtil.copy(data, UserBoxConfigAddReq.class);list.add(item);}@Overridepublic void doAfterAllAnalysed(AnalysisContext context) {log.info("表格成功解析");}public List<UserBoxConfigAddReq> getList() {return list;}
}
6、postman 接口调用
调用后成功解析获取到数据。
参考文章:基本使用
基本配置
使用演示
到此、告一段落,后期我们会分享其高级用法,敬请期待!