导出封装Poi逻辑

本次导出使用糊涂工具包的导出工具,对期进行小封装:

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExportProperty {
    /**
     * 导出字段名
     * @return
     */
    String name() default "";

    /**
     * 排序字段
     * @return
     */
    int sort() default 0;
}
public class User {
    @ExportProperty(name = "名字",sort = 0)
    private String name;
    @ExportProperty(name = "年龄",sort = 2)
    private int age;
    @ExportProperty(name = "地址",sort = 1)
    private String addr;

    public User() {
    }

    public User(String name, int age, String addr) {
        this.name = name;
        this.age = age;
        this.addr = addr;
    }
}
  File doTask() {
         List<User> list=new ArrayList<>();
        list.add(new User("xiaoming",18,"广东"));
        list.add(new User("鸿",19,"湖南"));
        list.add(new User("sss",27,"上海"));
        String fileName="test.xlsx";
        String filePath=System.getProperty("user.dir")+ File.separator+"temp1";
        File file=new File(filePath+File.separator + fileName);
        //通过工具类创建writer
        BigExcelWriter writer = ExcelUtil.getBigWriter(file);
        this.doAddAlias(list,writer);
        writer.write(list, true);
        writer.close();


       return file;

    }

    public  <T>void  doAddAlias(List<T> list, ExcelWriter excelWriter){
            if(CommonUtil.isNull(list)){
                return;
            }
        Class<?> aClass = list.get(0).getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        Arrays.stream(declaredFields).filter(a->a.isAnnotationPresent(ExportProperty.class)).sorted((k1,k2)->{
           int sort1=  k1.getAnnotationsByType(ExportProperty.class)[0].sort();
           int sort2=  k2.getAnnotationsByType(ExportProperty.class)[0].sort();
           return sort1-sort2;
        }).forEach(b->{
            ExportProperty exportProperty=  b.getAnnotationsByType(ExportProperty.class)[0];
            excelWriter.addHeaderAlias(b.getName(),exportProperty.name());
        });
    }

 

posted @ 2022-03-24 15:26  yangxiaohui227  阅读(84)  评论(0)    收藏  举报