HSSFWorkbook + 自定义注解 利用反射生成Excel表格

1.引入依赖


    org.apache.poi
    poi
    3.8

2.编写自定义注解

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.FIELD})
@Documented
public @interface ExcelHeader {

    String value() default "";
}

3.编写工具类

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

public class ExcelUtil {

    /**
     * 通用生成excel
     *
     * @param list Excel数据
     * @param cls  实体类class
     * @param   实体类
     */
    public static  void generateExcel(List list, Class cls) throws NoSuchMethodException,
            InvocationTargetException, IllegalAccessException, IOException {
        // 创建Excel对象
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("excel测试");
        // 创建表头
        HSSFRow header = sheet.createRow(0);

        // 获取字段
        Field[] fields = cls.getDeclaredFields();

        // Excel 标题集合
        List headers = new ArrayList<>();
        // 字段名集合
        List methodNames = new ArrayList<>();

        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            if (field.isAnnotationPresent(ExcelHeader.class)) {
                // 获取注解value值 即表头
                String value = field.getAnnotation(ExcelHeader.class).value();
                HSSFCell cell = header.createCell(i);
                cell.setCellValue(value);

                // 获取get方法
                String methodName = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
                methodNames.add(methodName);
            }
        }

        for (int i = 0; i < list.size(); i++) {
            T t = list.get(i);
            // 创建行
            HSSFRow row = sheet.createRow(i + 1);
            for (int j = 0; j < methodNames.size(); j++) {
                // 创建列
                HSSFCell cell = row.createCell(j);
                Method method = null;
                method = cls.getMethod(methodNames.get(j));
                Object invoke = method.invoke(t);
                if (invoke == null) {
                    cell.setCellValue("");
                } else {
                    cell.setCellValue(invoke.toString());
                }

            }
        }

        FileOutputStream fileOut = new FileOutputStream("C:/workbook.xls");
        wb.write(fileOut);
    }

}

4.测试实体类

public class Student {

    @ExcelHeader("姓名")
    private String name;

    @ExcelHeader("编号")
    private String stuNo;

    @ExcelHeader("年龄")
    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStuNo() {
        return stuNo;
    }

    public void setStuNo(String stuNo) {
        this.stuNo = stuNo;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

5.测试方法

public static void main(String[] args) {
        List students = new ArrayList<>();
        Student student = new Student();
        student.setName("张三");
        student.setStuNo("20210108");
        student.setAge("18");
        students.add(student);
        try {
            generateExcel(students,Student.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

6.输出结果

HSSFWorkbook + 自定义注解 利用反射生成Excel表格_第1张图片

 

你可能感兴趣的:(java,excel,反射)