背景:在项目中实现EXCEL的导出功能时经常会遇到字段与导出字段不符的的情况(例如:性别在数据库中存的是0,1但是实际导出要求男和女),针对这种现象之前项目采用对导出数据预处理(数据重新遍历在加判断一般结果集都是List<Map<String, Object>> ),然后在导出,这种方式对于只有个别情况却不得不在进行遍历一次原始数据的方式及其不合理。
需求:采用easyPOI基于注解的方式实现简化导出功能(其他功能参考相关API)
分析:通过浏览源码发现其实导出功能就是通过设置导出实体类,设置相关注解,然后导出时通过反射获得注解信息从而获得导出字段对应名称等等
实现步骤:
1、引入相关依赖
<!-- excel easypoi --> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-spring-boot-starter</artifactId> <version>4.3.0</version> </dependency>2、编写导出实体类(以用户信息表为例)
@ExcelTarget("users") @Data public class UserE { @Excel(name = "用户编号",needMerge = true) private Long id; @Excel(name = "用户名称",needMerge = true) private String username; @Excel(name = "手机号",needMerge = true) private String phone; @Excel(name = "性别",replace = { "男_1", "女_2" },needMerge = true) private String sex; }3、编写导出Controller代码
@RequestMapping("/export") public void export(HttpServletRequest request, HttpServletResponse response) throws IOException { List<User> list = userService.getAllUser(); List<UserE> list1 =new ArrayList<>(); for(User user:list){ UserE userE = new UserE(); userE.setId(user.getId()); List<Role> roleList= roleService.getRoleByUserId(user.getId()); List<RoleE> roleList1=new ArrayList<>(); list1.add(userE); } ExportParams exportParams = new ExportParams(); Workbook wb = ExcelExportUtil.exportExcel(exportParams, UserE.class, list1); String fileName="用户信息"; String userAgent = request.getHeader("USER-AGENT"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent, "Trident") || StringUtils.contains(userAgent,"Edge")){//IE 浏览器 fileName = URLEncoder.encode(fileName,"UTF8"); }else{//火狐,google等其他浏览器 fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); } response.setHeader("Content-Disposition", "attachment; filename=" + fileName); //客户端不缓存 response.setCharacterEncoding("UTF-8"); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); ServletOutputStream outputStream = response.getOutputStream(); wb.write(outputStream); wb.close(); outputStream.close(); }4、注意事项:
①前端请求获取响应流时需要设置响应方式为blob方式,否则导出会出现乱码或者[Object object]的情况
②如若设置的响应方式为blob但是仍响应了json方式,说明导出功能有错误需排查。
备注:简单记录一下,更多功能参看文档EasyPoi教程_V1.0
http://easypoi.mydoc.io/
http://easypoi.mydoc.io/
1万+




被折叠的 条评论
为什么被折叠?



