原 easyexcel(十一):easyexcel动态表头,表头合并
版权声明:本文为博主原创文章,请尊重他人的劳动成果,转载请附上原文出处链接和本声明。
本文链接:https://www.91mszl.com/zhangwuji/article/details/1319
一:效果图。我们的表头需要进行合并。
二:代码实现(方法一:代码有点冗余)
public ReturnMsgUtils testExcel(HttpServletResponse response, Map<String, Object> params, MultipartFile file) throws IOException {
String fileName=System.currentTimeMillis() + ".xlsx"; // excel文件名称
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment; filename*=utf-8''" + fileName);
OutputStream os=response.getOutputStream();
// 模拟数据
List<DemoMergeData> list = new ArrayList<DemoMergeData>();
for (int i = 0; i < 10; i++) {
DemoMergeData data = new DemoMergeData();
data.setName("张三");
data.setSex("男");
data.setAge(18);
data.setOne("1");
data.setTwo("2");
list.add(data);
}
// 合并表头[方法一]
List<List<String>> headList=new ArrayList<List<String>>();
List<String> list1=new ArrayList<>();
list1.add("姓名");
List<String> list2=new ArrayList<>();
list2.add("性别");
List<String> list3=new ArrayList<>();
list3.add("年龄");
List<String> list4=new ArrayList<>();
list4.add("月份");
list4.add("1月");
List<String> list5=new ArrayList<>();
list5.add("月份");
list5.add("2月");
headList.add(list1);
headList.add(list2);
headList.add(list3);
headList.add(list4);
headList.add(list5);
EasyExcel.write(os).head(headList).sheet("模板").doWrite(list);
ReturnMsgUtils result=new ReturnMsgUtils(BusinessUtils.CODE_200, BusinessUtils.MSG_EXPORT_200);
return result;
}
三:代码实现(方法二:推荐,代码比较精简】)
public ReturnMsgUtils testExcel(HttpServletResponse response, Map<String, Object> params, MultipartFile file) throws IOException {
String fileName=System.currentTimeMillis() + ".xlsx"; // excel文件名称
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment; filename*=utf-8''" + fileName);
OutputStream os=response.getOutputStream();
// 模拟数据
List<DemoMergeData> list = new ArrayList<DemoMergeData>();
for (int i = 0; i < 10; i++) {
DemoMergeData data = new DemoMergeData();
data.setName("张三");
data.setSex("男");
data.setAge(18);
data.setOne("1");
data.setTwo("2");
list.add(data);
}
// 合并表头[方法二]
List<List<String>> headList=new ArrayList<List<String>>();
headList.add(Lists.newArrayList("姓名"));
headList.add(Lists.newArrayList("性别"));
headList.add(Lists.newArrayList("年龄"));
headList.add(Lists.newArrayList("月份", "1月"));
headList.add(Lists.newArrayList("月份", "2月"));
EasyExcel.write(os).head(headList).sheet("模板").doWrite(list);
ReturnMsgUtils result=new ReturnMsgUtils(BusinessUtils.CODE_200, BusinessUtils.MSG_EXPORT_200);
return result;
}
注意:Lists.newArrayList是属于com.google.common.collect.Lists包下面的。
2021-05-07 18:04:08 阅读(8704)
名师出品,必属精品 https://www.91mszl.com
博主信息