背景
最新项目有个新需求,把项目中的数据通过excel的固定模板导出,懒懒的我不怎么会poi就使用easyexcel简化操作步骤
步骤
根据easyExcel的官方文档 https://www.yuque.com/easyexcel/doc/easyexcel
第一步 定义DataDemo,把要导出的数据定义为DataDemo类的字段
第二步 添加注解变量 @ExcelProperty("字符串标题"),模板如下
@Data
public class DataDemo{
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
@ExcelProperty("数字标题")
private Double doubleData;
/**
* 忽略这个字段
*/
@ExcelIgnore
private String ignore;
}
第三步:将要输出的数据形成多个DataDemo对象,并存入list集合
第四步:EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(list集合);
输出结果如下图:
很简单吧! 但是复杂头的Excel怎么写出呢? 类似这种
则DataDemo应该的定义成这样
@Data
public class ComplexHeadData {
@ExcelProperty({"主标题", "字符串标题"})
private String string;
@ExcelProperty({"主标题", "日期标题"})
private Date date;
@ExcelProperty({"主标题", "数字标题"})
private Double doubleData;
}
如果更复杂的头呢?
可以参考一下下面代码
public class MultiLineHeadExcelModel extends BaseRowModel {
@ExcelProperty(value = {"表头1","表头1","表头31"},index = 0)
private String p1;
@ExcelProperty(value = {"表头1","表头1","表头32"},index = 1)
private String p2;
@ExcelProperty(value = {"表头3","表头3","表头3"},index = 2)
private int p3;
@ExcelProperty(value = {"表头4","表头4","表头4"},index = 3)
private long p4;
@ExcelProperty(value = {"表头5","表头51","表头52"},index = 4)
private String p5;
@ExcelProperty(value = {"表头6","表头61","表头611"},index = 5)
private String p6;
@ExcelProperty(value = {"表头6","表头61","表头612"},index = 6)
private String p7;
@ExcelProperty(value = {"表头6","表头62","表头621"},index = 7)
private String p8;
@ExcelProperty(value = {"表头6","表头62","表头622"},index = 8)
private String p9;
}