easyexcel指定列导出的实现
Posted 反派的大佬
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了easyexcel指定列导出的实现相关的知识,希望对你有一定的参考价值。
Springboot继承easyexcel实现指定列导出功能:
前端传递需要导出的字段值,后端根据前端的传值导出对应的字段的值到Excel
-----核心代码-----
所需依赖:
<!--boot核心-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--<scope>runtime</scope>-->
</dependency>
<!--druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.3.0</version>
</dependency>
<!--阿里巴巴EasyExcel依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.6</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.6</version>
</dependency>
controller:
@GetMapping("/exportExcel")
public void exportExcel(Demo demo)
try
demoService.exportExcel(demo);
catch (Exception e)
e.printStackTrace();
domain
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
@Data
public class Demo
@ExcelIgnore
private int id;
@ExcelProperty("字段0")
private String o;
@ExcelProperty("字段1")
private String yi;
@ExcelProperty("字段2")
private String er;
service:
void exportExcel(Demo demo) throws JsonProcessingException;
impl:
public void exportExcel(Demo demo) throws JsonProcessingException
List<Demo> demos = demoMapper.demoList();
ObjectMapper mapper = new ObjectMapper();
//JAVA类转化为String类型键值对
String json = mapper.writeValueAsString(demo);
//String转化为json
JSONObject jsonObject= JSONObject.parseObject(json);
//获得json所有键
Set<String> keys = jsonObject.keySet();
//遍历获取所有值(用户传入的字段),并存入集合
Set<String> column = new HashSet<String>();
for (String key : keys)
if (jsonObject.get(key) != null)
column.add(jsonObject.get(key).toString());
//这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write("D:\\\\excel"+System.currentTimeMillis()+".xlsx", Demo.class)
.includeColumnFiledNames(column).sheet("模板")
.doWrite(demos);
mapper:
List<Demo> demoList();
mapper.xml:
<select id="demoList" resultType="com.excel.domain.Demo">
select * from sys_demo
</select>
-----测试-----
此时传入的值中,yi,er的值为对应的字段名
点击导出,导出成功
去导出的路径查看文件
打开即可看到,是我们想要的样子
以上是关于easyexcel指定列导出的实现的主要内容,如果未能解决你的问题,请参考以下文章
Spring Boot - 集成 EasyExcel 实现数据导入导出功能