Java Excel复杂表头,表头合并单元格
效果预览
一、maven依赖
<!--操作excel --><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.1.1</version><scope>test</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.1.1</version><scope>compile</scope></dependency>
二、Excel DTO
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;import java.util.Date;//导出数据成excel 多级头导出 配合测试类
@Data
public class DemoData {@ExcelProperty({"序号"})private Integer orderNumber;@ExcelProperty({"一级","二三四级"})private String ceshi;@ExcelProperty({"一级","二级头", "三级头","四级"})private String string;@ExcelProperty({"一级","二级头", "三级头","四级"})private Date date;@ExcelProperty({"一级","二级头", "三级头","四级"})private Double doubleData;@ExcelIgnoreprivate String ignore;
}
三、测试类
import java.util.ArrayList;
import java.util.Date;
import java.util.List;import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.merge.LoopMergeStrategy;public class Test {public static void main(String[] args) {Test.mergeWrite();System.out.println("hao");}//多级输出excelpublic static void mergeWrite() {//创建数据List<DemoData> list = new ArrayList<DemoData>();for (int i = 0; i < 10; i++) {DemoData data = new DemoData();data.setOrderNumber(i);data.setCeshi("测试");data.setString("测试" + i);data.setDate(new Date());data.setDoubleData(0.820);list.add(data);}//文件名String fileName = System.currentTimeMillis()+".xlsx";// 每隔2行会合并 把eachColumn 设置成 3 也就是我们数据的长度,所以就第一列会合并。当然其他合并策略也可以自己写LoopMergeStrategy loopMergeStrategy = new LoopMergeStrategy(2, 1);// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭EasyExcel.write(fileName, DemoData.class).registerWriteHandler(loopMergeStrategy).sheet("合并单元格").doWrite(list);}
}