优雅的生成excel模板,注解加hutool实现(一)
先给大家在这介绍一个很好用的工具包hutool工具包,用了段时间比较顺手,并且是中文注释。。。。。其中就有excel的封装工具。
官网地址:[(https://hutool.cn/docs)](入门和安装 (hutool.cn))
此次实现excel导出则是借助hutool工具包和poi实现
本次实现的maven依赖
<!--hu tool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.17</version>
</dependency>
<!--poi-->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
到这咱就可以开始生活做饭了
1、我们先实现个User.class实体类
package example.entity;
import lombok.Getter;
import lombok.Setter;
/**
* 用户实体类
*
* @author 讲真话的猫
* @since 2021/12/19 19:13
**/
@Setter
@Getter
public class User {
/**
*
* 用户主键id
*/
private Long id;
/**
* 用户名称
*/
private String name;
/**
* 用户年龄
*/
private Integer age;
/**
* 用户地址
*/
private String address;
}
2、实现注解,设置别名
import java.lang.annotation.*;
@Inherited
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelField {
/**
* 别名,excel表头名称
*/
String name() default "";
}
3、具体实现
public void exportExcel() {
ExcelWriter writer = ExcelUtil.getWriter();
Map<String, String> headerAlias = ExcelUtils.getHeaderAlias(User.class);
//设置字段别名
writer.setHeaderAlias(headerAlias);
//标题
writer.writeHeadRow(headerAlias.values());
writer.flush(new File("E:\\test\\test.xls"));
}
//ExcelUtils.getHeaderAlias获取注解的别名
public static Map<String, String> getHeaderAlias(Class<?> tClass) {
Field[] declaredFields = tClass.getDeclaredFields();
Map<String, String> stringMap = new LinkedHashMap<>();
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
ExcelField annotation = declaredField.getAnnotation(ExcelField.class);
if (annotation != null) {
String name = annotation.name();
stringMap.put(declaredField.getName(), name);
}
}
return stringMap;
}
4、实现效果