1. pom依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
2.准备模板
{.xxx}代表list填充,填入对应属性名;
{xxx}代表map填充(填入key)或者bean填充(填入属性名);
3.放置模板
注意:springBoot的Maven项目默认只会加载ClassPath同级⽬录下⽂件(配置那些),其他的需要配置resources标签
在我的项目中进行了全部加载;需要根据个人需求进行调整,下图是需要自己添加加载目录的情况:
ps:如果你和我的项目配置一样,但是项目运行时找不到模板文件,可以看下target打包中是否存在模板文件,如果不存在重新rebuild项目即可
4.java代码
@RequestMapping("/exportTbqyxx")
public ResultVO exportTbqyxx(@RequestBody List<JcsjlrQueryDTO> queryDTOS, HttpServletResponse response){
//查询要导出的数据
List<Tbqy> tbqyList = new ArrayList<>();
for (JcsjlrQueryDTO queryDTO : queryDTOS) {
Tbqy tbqy = jcsjlrBPO.queryTbqy(queryDTO.getTyxydm());
if(tbqy != null){
tbqyList.add(tbqy);
}
}
// 模板地址
String templateFileName = "template" + File.separator + "tbqyxxTemplate.xlsx";
//导出模板
ExcelWriter excelWriter = null;
try {
InputStream inputStream = new ClassPathResource(templateFileName).getInputStream();
excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate
(inputStream).build();
} catch (IOException e) {
return new ResultVO("导出文件异常"+e);
}
//读取Excel
WriteSheet writeSheet = EasyExcel.writerSheet().build();
//是否新增行
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
excelWriter.fill(tbqyList, fillConfig, writeSheet);
// 关闭流
excelWriter.finish();
return new ResultVO();
}