原 easyexcel(十六):使用table写入实现excel导出多表头
版权声明:本文为博主原创文章,请尊重他人的劳动成果,转载请附上原文出处链接和本声明。
本文链接:https://www.91mszl.com/zhangwuji/article/details/1459
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.1</version>
</dependency>
/**
* 功能:easyexcel使用table写入实现excel导出多表头
* 来源:https://91mszl.com
* @Author: zxb
* @Date: 2023-12-09 11:38:26
*/
@GetMapping("/download")
public void download(HttpServletResponse response) throws IOException {
String fileName = System.currentTimeMillis() + ".xlsx";
response.reset();
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
OutputStream os=response.getOutputStream();
List<UserInfo> dataList=new ArrayList<>();
UserInfo u1=new UserInfo();
u1.setName("张无忌");
u1.setAge(18);
u1.setAddress("上海市青浦区虹桥国际机场1号");
UserInfo u2=new UserInfo();
u2.setName("赵敏");
u2.setAge(20);
u2.setAddress("上海市黄浦区东方明珠大厦100号");
UserInfo u3=new UserInfo();
u3.setName(null);
u3.setAge(null);
u3.setAddress(null);
dataList.add(u1);
dataList.add(u2);
dataList.add(u3);
List<List<String>> head1List=new ArrayList<>();
head1List.add(Lists.newArrayList("姓名"));
head1List.add(Lists.newArrayList("年龄"));
head1List.add(Lists.newArrayList("地址"));
List<List<String>> head2List=new ArrayList<>();
head2List.add(Lists.newArrayList("姓名"));
head2List.add(Lists.newArrayList("年龄"));
head2List.add(Lists.newArrayList("地址"));
try (ExcelWriter excelWriter = EasyExcel.write(os).build()) {
// 把sheet设置为不需要头 不然会输出sheet的头 这样看起来第一个table 就有2个头了
WriteSheet writeSheet = EasyExcel.writerSheet("用户信息").needHead(Boolean.FALSE).build();
// 这里必须指定需要头,table 会继承sheet的配置,sheet配置了不需要,table 默认也是不需要
WriteTable writeTable0 = EasyExcel.writerTable(0).needHead(Boolean.TRUE).build();
writeTable0.setHead(head1List);
WriteTable writeTable1 = EasyExcel.writerTable(1).needHead(Boolean.TRUE).build();
writeTable1.setHead(head2List);
excelWriter.write(dataList, writeSheet, writeTable0);
excelWriter.write(dataList, writeSheet, writeTable1);
}
}
2023-12-09 12:47:08 阅读(542)
名师出品,必属精品 https://www.91mszl.com
博主信息