1.导入依赖,注意不要导入其他关于excel的依赖,会冲突
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
2. 编写实体类
@Data @ToString @AllArgsConstructor @NoArgsConstructor @HeadRowHeight(value = 35) // 表头行高 @ContentRowHeight(value = 25) // 内容行高 @ColumnWidth(value = 20) // 列宽 public class StudentEntity implements java.io.Serializable { /** * 学生姓名 */ @ExcelProperty(value={"学生信息表","名字"}, index=0) private String name; /** * 学生性别 */ @ExcelProperty(value={"学生信息表","性别"}, index=1) private int sex; @ExcelProperty(value={"学生信息表","生日"}, index=2) private Date birthday; @ExcelProperty(value={"学生信息表","进校日期"}, index=3) private Date registrationDate; }
3. 编写导出代码
@Test public void test5() { ArrayList<StudentEntity> list = new ArrayList<>(); StudentEntity studentEntity = new StudentEntity(); studentEntity.setName("aaa"); studentEntity.setBirthday(new Date()); studentEntity.setSex(1); studentEntity.setRegistrationDate(new Date()); list.add(studentEntity); WriteCellStyle headWriteCellStyle = new WriteCellStyle(); //设置背景颜色 headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex()); //设置头字体 WriteFont headWriteFont = new WriteFont(); headWriteFont.setFontHeightInPoints((short)13); headWriteFont.setBold(true); headWriteCellStyle.setWriteFont(headWriteFont); //内容策略 WriteCellStyle contentWriteCellStyle = new WriteCellStyle(); //设置 水平居中 contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER); HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle); EasyExcel.write("学生信息表.xlsx", StudentEntity.class).registerWriteHandler(horizontalCellStyleStrategy).sheet().doWrite(list); }
4.运行之后会在项目中生成
5.打开可以看到生成的excel如下
6.详情可见官网
EasyExcel · 语雀EasyExcel是一个基于Java的简单、省内存的读...https://www.yuque.com/easyexcel/doc/easyexcel
或者其他博主详细解析