直接上干货,首先pom文件引入依赖
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.1.1</version></dependency>
接下来是java代码
public void export(List<LiquidityNotchExportDetailDto> list, HttpServletResponse response) throws IOException{//文件名字String filename = "liquidityNotch_"+System.currentTimeMillis()+".xlsx";response.setHeader("Content-Disposition", "attachment; filename="+filename);// 响应类型,编码response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");EasyExcel.write(response.getOutputStream()).head(LiquidityNotchExportEasyExcelUtils.head()).sheet("缺口").doWrite(LiquidityNotchExportEasyExcelUtils.contentData(list));}
head
是excel里的头文件,doWrite
指定的是导出数据
头文件LiquidityNotchExportEasyExcelUtils.head()
简单点的是单层
public static List <List<String>> head( ){List<String> fixhead1 = Lists.newArrayList("产品简称", "产品简称");List<String> fixhead2 = Lists.newArrayList("产品代码", "产品代码");List<List<String>> headTitles = new LinkedList<>();headTitles.add(fixhead1);headTitles.add(fixhead2);return headTitles;}
这样就能导出一行两列数据
产品简称 | 产品代码
如果你是复杂点的双层表头,比如这样
那么这样子写
public static List <List<String>> head( ){List<String> fixhead1 = Lists.newArrayList("产品简称", "产品简称");List<String> fixhead2 = Lists.newArrayList("产品代码", "产品代码");List<List<String>> headTitles = new LinkedList<>();headTitles.add(fixhead1);headTitles.add(fixhead2);List<String> orderSpeaces = Lists.newArrayList("可变现资产", "到期负债");orderSpeaces.forEach(title->{headTitles.add( Lists.newArrayList( "第一日",title) );});}
以此类推等等
导出数据就没啥好说了,很简单的拼一下
public static List <List<String>> contentData(List<LiquidityNotchExportDetailDto> list){List<List<String>> contentList = Lists.newArrayList();for (LiquidityNotchExportDetailDto dto : list) {List<String> temp = Lists.newArrayList(dto.getPortName(), dto.getPortId());contentList.add(temp);}return contentList;}