创建Excel:基于POI+注解实现

这篇博客介绍了如何利用Apache POI库和自定义注解实现一个灵活、可配置且无需改动原有业务代码的Excel生成方案。通过在数据结构体上添加注解,设置表头和映射模板,可以轻松创建Excel文件,支持不同数据类型的处理,且具备高度复用性。
摘要由CSDN通过智能技术生成

目标

其实网上已经有很多excel相关的导出了,但大多数都是不够灵活的,代码也不一定适用于自己的业务,所以我想写一份通用的excel,你只需要引入,剩下的交给注解和配置即可。

所以我要实现以下几个目标:

  • 灵活性,表头可配置化,增删表头只需调整模版
  • 扩展性,可增对不同数据类型做不同处理
  • 复用性,支持所有已存在的数据结构体
  • 无入侵性,无需改动已有业务代码

思路

一个数据结构体,对应Excel一行数据,有了数据结构体,用反射填充数据即可
Excel的表头位置与属性字段需要配置,由程序员在注解上配置,当然,最好放在配置中心,你只需要copy代码改动就行。

所以,Excel生成只需要对应一个注解即可。
我这边用注解是 @ExcelFile

结构体生成Excel效果图

在这里插入图片描述
在这里插入图片描述
只需引入注解标记结构体即可实现

annotation

注释都在代码里,文件全名可以根据业务改

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author ximu
 * @date 2021/8/29
 * @description 标记类为一个Excel文件
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface ExcelFile {

    /**
     * 文件全名
     */
    String fileName() default "excel.xlsx";

    /**
     * excel使用的属性排列格式模板 格式: 字段名1{fileTemplateSplit}字段名2{fileTemplateSplit}字段名3
     * <p>
     * 示例:id|name
     * <p>
     * 说明表头index0=id,index1=name
     */
    String fileHeadTemplate() default "";

    /**
     * excel属性与表头映射模版 格式: 字段1{fileMappingSplit}映射名称1{fileTemplateSplit}字段1{fileMappingSplit}映射名称1
     * <p>
     * 示例:id=学号|name=学生姓名
     * <p>
     * 说明id属性映射表头为学号,name属性映射表头为学生姓名
     */
    String fileMappingTemplate() default "";

    /**
     * 模版字段分隔符,默认无需调整
     */
    String fileTemplateSplit() default "\\|";

    /**
     * 属性名称映射分隔符,默认无需调整
     */
    String fileMappingSplit() default "\\=";

}

Domain

结构体,根据实际的业务来吧,这里只是一个demo
fileHeadTemplatefileMappingTemplate要配置正确,最好是放在配置中心

import com.apache.poi.annotation.ExcelFile;
import lombok.Data;

/**
 * @author ximu
 * @date 2021/8/29
 * @description 学生信息
 */
@ExcelFile(fileHeadTemplate = "id|name", fileMappingTemplate = "id=学号|name=学生姓名")
@Data
public class StudentDTO {

    /**
     * 学号
     */
    private Long id;

    /**
     * 学生姓名
     */
    private String name;

}

exception(非必需)

统一异常处理,如果你的项目有了异常管理,可以忽略,非必需

/**
 * @author ximu
 * @date 2021/8/29
 * @description
 */
@Data
public class PoiException extends RuntimeException {

    private int errCode;

    private String msg;

    public PoiException(String msg) {
        this.errCode = 500;
        this.msg = msg;
    }
}

util

生成Excel的全局方法,其中AssertUtil相关的不是必须,可以排除
e.printStackTrace(); 可用log.err替换
FileOutputStream也可以根据实际情况替换

import com.apache.poi.annotation.ExcelFile;
import org.apache.poi.ss.usermodel.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ximu
 * @date 2021/8/29
 * @description Excel工具类
 */
public class ExcelUtil {

    /**
     * 构建excel
     *
     * @param collection 数据集
     * @return excel文件路径
     */
    public static String createExcel(Collection<?> collection) throws IOException {
        AssertUtil.notEmpty(collection, "excel数据不能为空!");
        Object object = collection.stream().findFirst().get();
        Class<?> clazz = object.getClass();
        AssertUtil.isTure(clazz.isAnnotationPresent(ExcelFile.class), "该对象不能生成Excel!");
        ExcelFile annotation = clazz.getAnnotation(ExcelFile.class);
        // 取到模板
        String headTemplate = annotation.fileHeadTemplate();
        // 取到模板上的所有对象属性
        String[] split = headTemplate.split(annotation.fileTemplateSplit());

        // 取到模板属性与名称的映射关系
        String fileTemplateSplit = annotation.fileMappingTemplate();
        String[] mappingSplit = fileTemplateSplit.split(annotation.fileTemplateSplit());
        Map<String, String> nameMappingMap = Arrays.stream(mappingSplit).map(x -> x.split(annotation.fileMappingSplit())).collect(Collectors.toMap(x -> x[0], x -> x[1]));
        // 创建excel
        Workbook workbook = WorkbookFactory.create(true);
        // 创建excel页
        Sheet sheet = workbook.createSheet("sheet1");

        Map<String, Field> fieldMap = ReflectionUtil.getFieldMap(object);
        int rowIndex = 0, colIndex = 0;
        // 填充表头
        for (String fieldName : split) {
            createCell(sheet, rowIndex, colIndex++, nameMappingMap.get(fieldName));
        }
        ++rowIndex;
        colIndex = 0;
        for (Object data : collection) {
            for (String fieldName : split) {
                Field field = fieldMap.get(fieldName);
                field.setAccessible(true);
                try {
                    Object val = field.get(data);
                    // 创建完之后列需要忘后移动 所以需要加一
                    createCell(sheet, rowIndex, colIndex++, val);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            ++rowIndex;
            colIndex = 0;
        }
        FileOutputStream out = new FileOutputStream(annotation.fileName());
        workbook.write(out);
        out.close();
        return annotation.fileName();
    }

    /**
     * 创建单元格
     *
     * @param sheet    页
     * @param rowIndex 行号,从0开始
     * @param colIndex 列号,从0开始
     * @param val      单元格的值
     */
    private static void createCell(Sheet sheet, int rowIndex, int colIndex, Object val) {
        Row row = sheet.getRow(rowIndex);
        if (row == null) {
            row = sheet.createRow(rowIndex);
        }
        Cell cell = row.getCell(colIndex);
        if (cell == null) {
            cell = row.createCell(colIndex);
            cell.setCellType(CellType.STRING);
        }
        cell.setCellValue(val == null ? "" : val.toString());
    }

}

反射工具类,搭配ExcelUtil使用,建议保留

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ximu
 * @date 2021/8/29
 * @description 反射工具类
 */
public class ReflectionUtil {

    public static Map<String, Field> getFieldMap(Object object) {
        Map<String, Field> fieldMap = new ConcurrentHashMap<>();
        refReflectionField(object, fieldMap);
        return fieldMap;
    }

    private static void refReflectionField(Object object, Map<String, Field> fieldMap) {
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            fieldMap.put(field.getName(), field);
        }
        Class<?> superclass = object.getClass().getSuperclass();
        if (superclass != null && !"java.lang.Object".equals(superclass.getName())) {
            refReflectionField(superclass, fieldMap);
        }
    }

}

断言工具类,如果已有其他断言工具类,可忽略,非必需

import com.apache.poi.exception.PoiException;

import java.util.Collection;

/**
 * @author ximu
 * @date 2021/8/29
 * @description
 */
public class AssertUtil {

    public static void isTure(boolean res, String msg) {
        if (!res) {
            throw new PoiException(msg);
        }
    }

    public static void notEmpty(Collection<?> data, String msg) {
        if (data == null || data.isEmpty()) {
            throw new PoiException(msg);
        }
    }

}

Demo

模拟一次DB查询,并导出excel

import com.apache.poi.domain.StudentDTO;
import com.apache.poi.util.ExcelUtil;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class ExcelDemo {

    public static void main(String[] args) {
        // 构建数据
        List<StudentDTO> studentDTOS = queryStudentInfoList();

        try {
            // 构建excel
            String excelFilePath = ExcelUtil.createExcel(studentDTOS);
            System.out.println("excel文件创建成功:" + excelFilePath);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("excel文件创建失败");
        }
    }

    /**
     * 模拟一个DAO查询
     *
     * @return 学生信息
     */
    static public List<StudentDTO> queryStudentInfoList() {
        List<StudentDTO> studentDTOList = new LinkedList<>();
        for (long i = 0; i < 10; i++) {
            StudentDTO studentDTO = new StudentDTO();
            studentDTO.setId(i);
            studentDTO.setName("学生" + i + "号");
            studentDTOList.add(studentDTO);
        }
        return studentDTOList;
    }
}
自己封装的excel导出/导入,可以根据注解来导出excel.本项目一共有13个类,里面还包含了一个反射工具,一个编码工具,10分值了。下面是测试代码 public class Test { public static void main(String[] arg) throws FileNotFoundException, IOException{ testBean(); testMap(); } public static void testBean() throws FileNotFoundException, IOException{ List l = new ArrayList(); for(int i=0;i<100;i++){ l.add(new MyBean()); } //很轻松,只需要二句话就能导出excel BeanExport be = ExportExcel.BeanExport(MyBean.class); be.createBeanSheet("1月份", "1月份人员信息").addData(l); be.createBeanSheet("2月份","2月份人员信息").addData(l); be.writeFile("E:/test/bean人员信息8.xlsx"); } //如果不想用注解,还能根据MAP导出. public static void testMap () throws FileNotFoundException, IOException{ List l = new ArrayList(); l.add(new MapHeader("姓名","name",5000)); l.add(new MapHeader("年龄","age",4000)); l.add(new MapHeader("生日","birthdate",3000)); l.add(new MapHeader("地址","address",5000)); l.add(new MapHeader("双精度","d",4000)); l.add(new MapHeader("float","f",6000)); List<Map> lm = new ArrayList<Map>(); for(int i=0;i<100;i++){ Map map = new HashMap(); map.put("name","闪电球"); map.put("age",100); map.put("birthdate",new Date()); map.put("address","北京市广东省AAA号123楼!"); map.put("d",22.222d); map.put("f",295.22f); lm.add(map); } MapExport me = ExportExcel.mapExport(l); me.createMapSheel("1月份","广东省人员信息").addData(lm); me.createMapSheel("2月份", "北京市人员信息").addData(lm); me.writeFile("E:/test/map人员信息9.xlsx"); } }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值