需求背景
在使用EasyExcel进行导出Excel文件时如果不使用实体类的方式去导出,而是使用List的方式导出那么每个sheet里面的dataList是一个List
测试类
People.java
package test.main;
public class People {
private Integer id;
private String name;
private String sex;
private Integer age;
public People(Integer id, String name, String sex, Integer age) {
super();
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
实现方法
实现过程中依赖于FastJson依赖包,请自行添加依赖
public static List<List<String>> makeSheetDataList(List<?> list, String[] fields, Class<?> classType) {
List<List<String>> dataList = new ArrayList<>();
String temp = JSONObject.toJSONString(list);
List<?> objects = JSONArray.parseArray(temp, classType);
for (Object object : objects) {
Map<String, String> map = JSONObject.parseObject(JSONObject.toJSONString(object),
new TypeReference<Map<String, String>>() {
});
List<String> tempList = new ArrayList<>();
for (String field : fields) {
tempList.add(map.get(field));
}
dataList.add(tempList);
}
return dataList;
}
运行效果
public static void main(String[] args) {
People p1 = new People(1, "huhailong", "man", 26);
People p2 = new People(2, "wuxinhua", "man", 26);
List list = new ArrayList<>();
list.add(p1);
list.add(p2);
String[] fields = { "id", "name", "sex", "age" };
List<List<String>> makeSheetDataList = makeSheetDataList(list, fields, People.class);
System.out.println(makeSheetDataList);
}
运行结果
[[1, huhailong, man, 26], [2, wuxinhua, man, 26]]
使用该方法时需要传递三个参数:
- list:需要转化的集合
- fields:对应的字段属性名,这里的顺序对应输出到excel表格中的顺序
- classType:对应的类型
Original: https://www.cnblogs.com/hhl1011/p/16478912.html
Author: 胡海龙
Title: 将实体类集合List<?>转为集合嵌套List<List<String>>(可用于EasyExcel导出数据时SheetData使用)
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/588011/
转载文章受原作者版权保护。转载请注明原作者出处!