问题背景:
在我们日常开发中可能会遇到需要将数据导出为excel的情况 之前也是知识浅薄,查阅了相关文献,特此记录与大家共享。
问题实现:
1. 首先我们需要找出依赖的pom文件
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
注意:EasyExcel需要与poi版本适应 否则会产生例如:Io not close 一系列的问题。
2. 实现类方法
@Override
public String exportExcelInfo(HttpServletResponse response, List<Person> list) {
ClassPathResource resource = new ClassPathResource("template/dict.xlsx");
try (InputStream in = resource.getInputStream()) {
List<Person> data = Lists.newArrayList();
String fileName = "模板";
fileName = new String(fileName.getBytes(StandardCharsets.UTF_8));
//此处为默认值
if (list == null) {
Person person = new Person();
person.setName("张三");
person.setAge("18");
data.add(person);
} else {
data = list;
}
response.setContentType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName.replaceAll("\\+", "%20") + ".xlsx");
EasyExcel.write(response.getOutputStream()).withTemplate(in).sheet("Sheet1")
.doFill(data);
} catch (Exception e) {
throw new CstException(ResultCodeEnum.SYSTEM_FAILURE.getCode(), "文档格式或数据有误,请检查");
}
return "success";
}
注意:此时我是将文件放入代码中resourse里的 具体需要根据实际情况来选择模板位置
3.模板中的内容 需要将需要填充的数据以这种形式展现 具体可以参考官网
大功告成!希望能够帮助到各位,有具体问题欢迎留言
如果需要解析excel中的数据的话 可以跳转这个地址 Excel数据解析-CSDN博客