对象列表,JSON转成excel表工具类
最近做一个功能需要将数据库的数据转换成excel,突发奇想,做一个工具类,以后遇到对象列表转换成exce以及json转换成excel都可以直接使用。
前置依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
对象必须具有转换成excel的能力
创建excel需要第一行标题行和以下的数据,这里封装成了接口ExcelAble,提供了getHeads()获取标题行和getData()获取数据。以下默认使用反射获取所有字段作为标题行,默认使用对象的相应的反射get方法作为数据。也可以重写方法实现自定义和用get方法提升效率。
public interface ExcelAble {
/**
* 默认excel表头是对象所有字段,可自定义需要的表头字段
*
* @return excel表头列表
*/
default List<String> getHeads() {
List<String> result = new ArrayList<>();
Class<? extends ExcelAble> aClass = this.getClass();
Field[] fields = aClass.getDeclaredFields();
for (Field field : fields) {
result.add(field.getName());
}
return result;
}
/**
* 默认使用反射获取对象字段值,可重写使用get方法提升效率
*
* @return excel一列数据值
*/
default List<String> getData() {
List<String> result = new ArrayList<>();
Class<? extends ExcelAble> aClass = this.getClass();
List<String> fields = this.getHeads();
Method[] methods = aClass.getDeclaredMethods();
for (String field : fields) {
for (Method method : methods) {
if (method.getName().toLowerCase().equals(("get" + field).toLowerCase())) {
try