1、首先加入EasyExcel 的 pom依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.0.5</version> </dependency>2、创建导出数据对应的实体类
@Data public class UserExcelVo { @ExcelProperty(value = "序号", index = 0) private String number; @ExcelProperty(value = "姓名", index = 1) private String username; @ExcelProperty(value = "年龄", index = 2) private String age; @ExcelProperty(value = "工资", index = 3) private String salary; @DateTimeFormat("yyyy-MM-dd HH:mm:ss") // 格式化日期 @ExcelProperty(value = "创建时间", index = 4) private Date createTime; }
3、调用生成方法
// 表示要导出的数据源 List<UserExcelVo> resultList = new ArrayList(); // 定义输出文件名称 String excelName = "用户信息导出-" + DateUtils.formatDate(new Date(), "yyyy-MM-dd") + ".xlsx"; // 导出本地文件 File file = new File("/Users/lilu/Desktop/" + excelName); // 此处用自动适应列宽的策略 EasyExcelFactory.write(file, UserExcelVo.class). registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("sheet名称").doWrite(resultList); // web页面导出 /*ServletOutputStream out = null; try { String excelName = "原始开票数据导出-" + DateUtils.formatDate(new Date(), "yyyy-MM-dd") + ".xlsx"; response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(excelName, "utf-8")); out = response.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } // 此处用自动适应列宽的策略 EasyExcelFactory.write(out, UserExcelVo.class). registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("sheet名称").doWrite(resultList);*/