SpringBoot整合Easypoi,Excel文件导出
https://www.yuque.com/easyexcel/doc/write
1、加入jar
<dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-spring-boot-starter</artifactId> <version>4.1.3</version> </dependency> |
2、编写代码
实体类编写:
/* * @author tiankx * @description 学生 * @date 20200925 * */ @Setter @Getter @AllArgsConstructor @NoArgsConstructor public class Student { //name : 列名 , orderNum : 列名在第几列 , needMerge : 需要合并 @Excel(name="姓名" , orderNum = "1" , width = 30 ,needMerge = true) private String name ; @Excel(name="年龄" , orderNum = "2" , width = 30 ,needMerge = true) private int age ; @Excel(name="性别" , orderNum = "3" , width = 30 ,needMerge = true) private int sex ; } |
导出实现代码:
@GetMapping("/Export") public void getExportFile(HttpServletResponse response){ //准备数据源 List<Student> students = new ArrayList<>(); int sex = 0 ; for (int i = 0 ; i < 100 ; i ++){ sex = i % 2 == 1 ? 1:0 ; students.add(new Student("zs"+i , 18+i ,sex)); } try { //判断数据源是否非空 Collections是commos.collections4 .jar中的 if (CollectionUtils.isNotEmpty(students)) { //导出配置 response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-Disposition", //test_name :文件导出后的名称 "attachment;filename=" + URLEncoder.encode("test_name", "UTF-8")); //Excel表名 ExportParams params = new ExportParams("班级详情导出", "班级详情导出"); //封装数据 Workbook workbook = ExcelExportUtil.exportExcel(params, Student.class, students); //将数据写入输出流 workbook.write(response.getOutputStream()); }else{ log.error("没有可以导出的数据"); return; } } catch (Exception e) { e.printStackTrace(); } |