我们采用的hutool的工具类,对实体类和map进行的excel导出操作
首先创建一个实体类:
@Data//实现了:1、所有属性的get和set方法;2、toString方法;3、hashCode方法;4、equals方法@Builder//建造者模式@NoArgsConstructor//无参构造函数@AllArgsConstructor//有参构造函数publicclassUserInfo{privateStringname;privateIntegerage;privateStringidCard;privateStringgender;privateStringbirthday;}
然后,我们以接口的形式进行调用
@RestController@RequestMapping(value="/excel")publicclassTestExcel{@GetMapping(value="/export")publicvoidexcelExport(HttpServletResponseresponse){//以map的方式Map<String,Object>row1=newLinkedHashMap<>();row1.put("姓名","苹果");row1.put("颜色","红/黄/绿");row1.put("口感","酸甜");row1.put("产地","全国");Map<String,Object>row2=newLinkedHashMap<>();row2.put("姓名","香蕉");row2.put("颜色","黄");row2.put("口感","甜");row2.put("产地","南方");ArrayList<Map<String,Object>>rows_1=CollUtil.newArrayList(row1,row2);UserInfouserInfo=newUserInfo();userInfo.setName("张三");userInfo.setAge(10);userInfo.setGender("男");userInfo.setIdCard("3013");List<UserInfo>rows_2=newArrayList<>();rows_2.add(userInfo);//通过工具类创建writer,默认创建xls格式ExcelWriterwriter=ExcelUtil.getWriter();writer.setSheet("sheet1");writer.merge(3,"水果信息");//一次性写出内容,使用默认样式,强制输出标题writer.write(rows_1,true);writer.setSheet("sheet2");writer.addHeaderAlias("name","姓名");writer.addHeaderAlias("age","年龄");writer.addHeaderAlias("idCard","证件号");writer.addHeaderAlias("gender","性别");writer.addHeaderAlias("birthday","生日");writer.merge(4,"人员信息");writer.write(rows_2,true);//response为HttpServletResponse对象response.setContentType("application/vnd.ms-excel;charset=utf-8");//test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码response.setHeader("Content-Disposition","attachment;filename=test.xls");ServletOutputStreamout=null;try{out=response.getOutputStream();writer.flush(out,true);}catch(Exceptione){e.printStackTrace();}finally{//关闭writer,释放内存writer.close();//此处记得关闭输出Servlet流IoUtil.close(out);}}}
注意:我们第一个sheet用的map,第二个sheet用的实体类
接下来,我们使用postman进行调用
然后生成的excel如下: