需求
我们经常会遇到需要生成excel文件的需要,这个时候通常会使用apache提供的poi,但原生poi提供的api使用起来比较繁琐,所以我们实现利用注解的方式来快速封装
对象注入
@ExcelName 单页excel的名称 @ExcelRow 每行标题以及位置
@ExcelName("user list")
public class ReportData {
@ExcelRow(headerName = "User Name", columnIndex = 0)
private String username;
@ExcelRow(headerName = "Age", columnIndex = 1)
private int age;
@ExcelRow(headerName = "Sex", columnIndex = 2)
private String sex;
@ExcelRow(headerName = "User Id", columnIndex = 3)
private String userId;
}
复制代码
调用封装方法
在封装的方法中传入对象的class,包含数据的list数组reportData,再输出到一个输出流就完成了
ExcelUtil.newSingleExcel(ReportData.class)
.fillData(reportData)
.flush(outputStream);
复制代码
具体代码实现
定义两个我们需要的注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelName {
String value() default "";
}
复制代码
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelRow {
String headerName() default "";
int columnIndex();
}
复制代码
核心ExcelUtil类
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apach