基于前后端分离向前端返回excel数据流
前言:本文介绍的是阿里的第三方框架EasyExcel
1.引入EasyExcel依赖
这里使用pom依赖(这里我排除了项目已有的依赖)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.5</version>
<exclusions>
<exclusion>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
2.Service层代码
/**
* 导出报表 使用easy excel框架
* @param
* @return
*/
public BaseResponse exportExcel(Integer idCommunity,String idVillage,Integer yearFlag, HttpServletResponse resp) {
//设置文件生成路径
//数据库查询视图
List<ViewPartyMemberYear> excel =null ;
if(yearFlag==-1)
excel= partyDao.exportExcelLastYear(idCommunity, idVillage);
else
excel= partyDao.exportExcelThisYear(idCommunity, idVillage);
resp.reset();
resp.setCharacterEncoding("UTF-8");
//响应内容格式
resp.setContentType("application/vnd.ms-excel");
//设置文件名
String fileName =System.currentTimeMillis() + ".xlsx";
try {
//设置前端下载文件名
resp.setHeader("Content-disposition", "attachment;filename=" +new String(fileName.getBytes("UTF-8"), "GBK"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return BaseResponse.fail("导出失败");
}
try {
//向前端写入文件流流
EasyExcel.write(resp.getOutputStream(), ViewPartyMemberYear.class)
.sheet("积分表").doWrite(excel);
} catch (IOException e) {
e.printStackTrace();
return BaseResponse.fail("导出失败");
}
return BaseResponse.Ok("导出成功");
}
之前是在后端生成excel文件,然后将该文件以流的形式返回到前端。但该框架还有另外的doWrite()方法,直接返回流。
