当前位置:网站首页>Easyexcel exports according to the filter column (not empty in the middle, the order can be adjusted)
Easyexcel exports according to the filter column (not empty in the middle, the order can be adjusted)
2020-11-09 16:11:00 【T bean sprouts】
Use EasyExel According to the way the filter column is exported, there is one in the official document “ Export only the specified columns according to the parameters ” Example , But in this case, I tested the derived Excel That's true .
EasyExcel Official documents :https://www.yuque.com/easyexcel/doc
“ name ” and “ Birthday ” In the middle, there's a column , But if you need to export according to which fields are displayed on the front end , And the order should be as shown on the front end ( The front end implements drag and drop as well as filter to specify which fields to display , Therefore, the export format should be consistent ...), The example given in this official document does not seem to satisfy , So I wrote an example that uses no object creation + An example of how reflection works .
This is one I wrote Person Test object
public class Person {
@ExcelIgnore
private Long id;
@ExcelProperty(" name ")
private String name;
@ExcelProperty(" Age ")
private int age;
@ExcelProperty(" Birthday ")
@DateTimeFormat("yyyy year MM month dd Japan ")
private Date birthday;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
Using official documents “ Do not create write for objects ” Example , Encapsulate the , Use reflection to return the fields to be filtered
package com.example.demo.utils;
import com.alibaba.excel.EasyExcel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* @author Bean sprouts
* @version 1.0
* @Date 2020-11-09 09:13
*/
public class EasyExcelUtils {
private static final Logger logger = LoggerFactory.getLogger(EasyExcelUtils.class);
/**
* @param fileName File pathname
* @param sheetName sheet name
* @param data The data from the query
* @param headList Incoming Excel head ( for example : full name , Birthday )
* @param fileList Pass in the fields to be displayed ( for example : The field corresponding to the name is name, The corresponding field of birthday is birthday)
*/
public static void noModelWrite(String fileName, String sheetName, List data, List<String> headList, List<String> fileList){
EasyExcel.write(fileName).head(head(headList)).sheet(sheetName).doWrite(dataList(data,fileList));
}
/**
* Set up Excel head
* @param headList Excel Header information
* @return
*/
private static List<List<String>> head(List<String> headList) {
List<List<String>> list = new ArrayList<>();
for (String value : headList) {
List<String> head = new ArrayList<>();
head.add(value);
list.add(head);
}
return list;
}
/**
* Set table information
* @param dataList The data found
* @param fileList Fields to display
* @return
*/
private static List<List<Object>> dataList(List<Object> dataList, List<String> fileList) {
List<List<Object>> list = new ArrayList<>();
for (Object person : dataList) {
List<Object> data = new ArrayList<>();
for (String fieldName : fileList) {
/** By reflecting the fields that are displayed as needed , Get the corresponding property value */
data.add(getFieldValue(fieldName, person));
}
list.add(data);
}
return list;
}
/**
* According to the field passed in, get the corresponding get Method , Such as name, Corresponding getName Method
* @param fieldName Field name
* @param person object
* @return
*/
private static Object getFieldValue(String fieldName, Object person) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = person.getClass().getMethod(getter);
return method.invoke(person);
} catch (Exception e) {
logger.error(" Failed to get object property value using reflection ", e);
return null;
}
}
}
controller Layer uses this tool class to write Excel.
@RequestMapping(value = "/auth/downloadList",method = {RequestMethod.GET, RequestMethod.POST})
public void downloadList(String filedNames,String filedCodes){
List<Person> list = personServiceImpl.findPersonAll();
/**Excel head , Parameter format : full name , Birthday */
String[] head = filedNames.split(",");
List<String> headList = new ArrayList<>(Arrays.asList(head));
/**Excel Form and content , Parameter format :name,birthday*/
String[] file = filedCodes.split(",");
List<String> fileList = new ArrayList<>(Arrays.asList(file));
EasyExcelUtils.noModelWrite("E:/data/ Test example .xls"," Test example ",list,headList,fileList);
}
test 1 The incoming parameter is :
filedNames : name , Birthday
filedCodes : name,birthday
The effect is as follows :
test 2 The incoming parameter is :
filedNames : Birthday , name
filedCodes : birthday,name
The effect is as follows :
Through the code above , Use EasyExcel Does not create object write for + Reflection technology can be implemented without leaving one or more columns empty Excel, The dynamic column display can be realized according to the order of the front-end input parameters .
Be careful :
1. To use this method, you need to pass in Excel Header information and corresponding field information ;
2. Because we use reflection to call the corresponding property name get Method to get the value , You need to check the properties corresponding to get Whether the method is named canonically , If not, it needs to be dealt with separately .
版权声明
本文为[T bean sprouts]所创,转载请带上原文链接,感谢
边栏推荐
- The technology masters who ride the wind and waves gather again | Tencent cloud TVP continues to sail
- Using fastai to develop and deploy image classifier application
- 自定义室内地图在线工具
- 低功耗蓝牙单芯片为物联网助力
- 在Python中创建文字云或标签云
- 深入分析商淘多用户商城系统如何从搜索着手打造盈利点
- Source code analysis of serilog -- implementation of sink
- 高质量的缺陷分析:让自己少写 bug
- 缓存的数据一致性
- Exhibition cloud technology interpretation | in the face of emergencies, how does app do a good job in crash analysis and performance monitoring?
猜你喜欢
知识图谱描边1.1——从NER上手
如何设计并实现存储QoS?
Toolkit Pro helps interface development: shorten the project development cycle and quickly realize GUI with modern functional area style
MES系统在行业应用里区别于传统式管理
Help enterprises to get rid of difficulties, famous enterprises return home Engineers: success depends on it!
AE(After Effects)的简单使用——记一次模板套用的过程
Solution to the failure of closing windows in Chrome browser JS
缓存的数据一致性
Full stack technology experience tells you: how much does it cost to develop a mall small program?
Toolkit Pro助力界面开发:缩短项目开发周期,快速实现具有现代功能区样式的GUI
随机推荐
A quick start to Shell Scripting
一款基于.NET Core的认证授权解决方案-葫芦藤1.0开源啦
堆重启_uaf_hacknote
5 minutes get I use GitHub's 5-year summary of these operations!
自定义室内地图在线工具
会展云技术解读 | 面对突发事故,APP 如何做好崩溃分析与性能监控?
.NET报表生成器Stimulsoft Reports.Net 发布最新版v2020.5!
深入分析商淘多用户商城系统如何从搜索着手打造盈利点
Application and practice of native map and web fusion technology
最新版PyCharm 2020.3 :可实现结对编程,智能文本校对等|附下载体验
轻松构建高颜值应用界面,这些内置图标多重要!
树莓派内网穿透建站与维护,使用内网穿透无需服务器
Toolkit Pro helps interface development: shorten the project development cycle and quickly realize GUI with modern functional area style
Application of pull wire displacement sensor in slope cracks
Performance comparison of serialization tools such as Jackson, fastjson, kryo, protostuff
MES system is different from traditional management in industry application
浮点数之间的等值判断
校准服务的六个轴心
Service registration and discovery of go micro integration Nacos
脑机接口先驱炮轰马斯克:“他走的是一条死胡同,说的话我一个字都不同意”