使用Hutool对表格进行带别名的写入,通过注解自动解析别名

使用Hutool对表格进行带别名的写入

1.创建别名的注解类@ExcelAlias

package com.hsh.excelutil.Anno;

import java.lang.annotation.*;

/**
 * @Author hsh
 * @DateTime 2023/09/05 17:15
 **/
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelAlias {

    String value()  default "";

}

2.创建实体类Student,其中name字段设置别名为“名字”

package com.hsh.excelutil.pojo;

import com.hsh.excelutil.Anno.ExcelAlias;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Author hsh
 * @DateTime 2023/09/02 20:51
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    @ExcelAlias(value = "名字")
    private String name;
    @ExcelAlias(value = "年龄")
    private Integer age;
}


3.创建工具类HuToolExcelUtil,其中有三个方法:redaExcel(),writeExcel(),getHeaderAlias()

package com.hsh.excelutil.util;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.hsh.excelutil.Anno.ExcelAlias;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.ReflectPermission;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author hsh
 * @DateTime 2023/09/09 14:56
 **/
public class HuToolExcelUtil {

    /**
     * 读取Excel并转化为list
     * 需要指定返回时元素的类
     *
     * @param path     需要读取的Excel 的路径aa
     * @param beanType 指定的类,
     * @return list
     */
    public static <T> List<T> redaExcel(String path, Class<T> beanType) {
        File file = new File(path);
        ExcelReader reader = ExcelUtil.getReader(file);
        reader.setHeaderAlias(getHeaderAlias(beanType, true));
        List<T> list = reader.readAll(beanType);
        reader.close();
        return list;
    }

    /**
     * 将list写入Excel中
     *
     * @param path 需要写入的Excel 的路径
     * @param list 写入的内容
     * @return
     */
    public static <T> void writeExcel(String path, List<T> list, Class<T> beanType) {
        Map headerAlias = getHeaderAlias(beanType, false);
        try (OutputStream out = new FileOutputStream(path); ExcelWriter writer = ExcelUtil.getWriter()) {
            writer.setHeaderAlias(headerAlias);
            // 写入并刷盘
            writer.write(list)
                    .flush(out);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获得一个类所有 有别名的 字段 和 别名
     *
     * @param beanType 类
     * @param isRead   每个键值对格式为 ("已有的","想改的")
     *                 true 读取时 每个键值对格式为:(“别名”, “字段名”), 从excel中读取到“已有的(别名)”, 改为“想改的(字段名)”
     *                 false 写入时 每个键值对格式为:(“字段名”, “别名”), 每个字段对应的“已有的(字段名)”, 改为“想改的(别名)”
     * @param <T>
     * @return
     */
    static <T> Map<String, String> getHeaderAlias(Class<T> beanType, boolean isRead) {
        Map headerAlias = new HashMap<String, String>();
        // Hutool 获取字段集合的方法,无需try/catch
        List<Field> fields = Arrays.asList(ReflectUtil.getFields(beanType));
        if (fields.isEmpty()) {
            return headerAlias;
        }
        for (Field field : fields) {
            // 获得每个字段的 @ExcelAlias注解
            ExcelAlias anno = field.getAnnotation(ExcelAlias.class);
            if (anno == null || "".equals(anno.value())) {
                continue;
            }
            if (isRead) {
                // 读取时 每个键值对格式为:(“别名”, “字段名”)
                headerAlias.put(anno.value(), field.getName());
            } else {
                // 写入时 每个键值对格式为:(“字段名”, “别名”)
                headerAlias.put(field.getName(), anno.value());
            }
        }
        return headerAlias;
    }

}

编写controller层测试

package com.hsh.excelutil.controller;

import com.hsh.excelutil.pojo.Student;
import com.hsh.excelutil.util.HuToolExcelUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author hsh
 * @DateTime 2023/08/29 17:39
 **/
@RestController
public class TestController {

    @GetMapping("/test")
    public void test() {
        List<Student> students1 = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            students1.add(new Student("名字"+i,i));
        }
        //写入
        HuToolExcelUtil.writeExcel("E:\\1.xlsx", students1, Student.class);
        //读取
        students1 = HuToolExcelUtil.redaExcel("E:\\1.xlsx", Student.class);
        //控制台打印
        System.out.println(students1);
    }
}

测试结果
测试结果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值