ist.forEach(System.out::println);
}
}
3、解析监听
继承AnalysisEventListener
类,并重写其中的方法,可以监听Excel的解析过程,或者添加一些自定义的处理逻辑;
public class DataListener extends AnalysisEventListener<DataVO> {
/**
* 接收解析的数据块
*/
@Override
public void invoke(DataVO data, AnalysisContext context) {
System.out.println("DataListener:"+data);
}
/**
* 接收解析的表头
*/
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
System.out.println("DataListener:"+headMap);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
System.out.println("DataListener:after...all...analysed");
}
}
4、导入导出
实际上Excel文件的导入导出,原理与文件的上传下载类似,只不过这里使用easyexcel
组件中的API来直接处理Excel的写和读;
@RestController
public class ExcelWeb {
@GetMapping("excel/download")
public void download(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("Excel数据", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), DataVO.class).sheet("用户").doWrite(DataVO.getSheet1List());
}
@ResponseBody
@PostMapping("excel/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
List<DataVO> dataList = EasyExcel
.read(file.getInputStream(), DataVO.class, new DataListener()).sheet().doReadSync();
dataList.forEach(System.out::println);
return "success";
}
}
使用Postman测试单个Excel上传接口:
五、参考源码
文档仓库:
https://gitee.com/cicadasmile/butte-java-note
源码仓库:
https://gitee.com/cicadasmile/butte-spring-parent