easyPoi自定义表头导出(包含数据字典转换、排序)等

475 阅读3分钟

1.实体对象TestModel

import cn.afterturn.easypoi.excel.annotation.Excel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 *@Author: chenlf
 *@CreateTime: 2022-11-28
 *@Description: 自定义导出对象
 *@Version: 1.0
 */
@Data
public class TestModel{

    @Excel(name = "编号", orderNum = "1", width = 10)
    @ApiModelProperty(value = "编号")
    private String no;

    @Excel(name = "标题", orderNum = "2", width = 50)
    @ApiModelProperty(value = "标题")
    private String title;

    @Excel(name = "公开范围", dict = "is_public", orderNum = "3", width = 10)
    @ApiModelProperty(value = "公开范围")
    private String publicScope;
}

工具类ExcelPoiUtil

  • getExportHeads 获取自定义表头所有字段【给前端自定义选择用的】
    • ①notExportFieldNames:预留了特殊情况下不需要导出的属性剔除,不需要该功能的,可将其删除即可,不影响。
    • ②exportFieldNames:一开始是打算处理前端返回来的结果,后面加了getExportEntitys去处理,去掉也不影响。
  • getExportEntitys 根据需要导出的字段生成ExcelExportEntity数组(这里去拿原来实体对象的排序,数据字典,还有宽度)

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *@Author: chenlf
 *@CreateTime: 2022-11-28
 *@Description: TODO
 *@Version: 1.0
 */
public class ExcelPoiUtil {

    /**
     * @title: getExportHeads
     * @description: 自定义设置导出表头
     * @author: chenlf
     * @date: 2022/11/28
     * @param: tClass 对象
     * @param: exportFieldNames 需要导出的属性(如果为null,则获取所有)
     * @param: notExportFieldNames 不需要导出的属性
     * @return: java.util.Map<java.lang.String,java.lang.String>
     */
    public static List<ExcelExportEntity> getExportEntitys(Class tClass, List<String> exportFieldNames, List<String> notExportFieldNames) {
        List<ExcelExportEntity> results = new ArrayList<>();
        //是否全部导出
        boolean allExport = (null != exportFieldNames && !exportFieldNames.isEmpty())?false:true;
        //是否存在不需要导出的属性
        boolean exitsNotExport = (null != notExportFieldNames && !notExportFieldNames.isEmpty())?true:false;
        Field[] fields = tClass.getDeclaredFields();
        Map<String, String> resultMap = new HashMap();
        for (Field field : fields) {
            System.out.println(field.getName());
            // 是否引用Excel注解
            if (field.isAnnotationPresent(Excel.class)) {
                Field f = ExcelPoiUtil.getFieldOfCheck(field, allExport, exitsNotExport, exportFieldNames, notExportFieldNames);
                if (null != f) {
                    Excel annotation = f.getAnnotation(Excel.class);
                    ExcelExportEntity excelExportEntity = new ExcelExportEntity(annotation.name(),field.getName());
                    excelExportEntity.setOrderNum(Integer.parseInt(annotation.orderNum()));
                    excelExportEntity.setWidth((double)annotation.width());
                    excelExportEntity.setDict(annotation.dict());
                    results.add(excelExportEntity);
                }
            }
        }
        return results;
    }

    /**
     * @title: getExportHeads
     * @description: 获取添加了Excel注解的所有属性
     * @author: chenlf
     * @date: 2022/11/28
     * @param: tClass对象
     * @param: exportFieldNames 需要导出的属性(如果为null,则获取所有)
     * @param: notExportFieldNames 不需要导出的属性
     * @return: java.util.Map<java.lang.String,java.lang.String>
     */
    private static Map<String, String> getExportHeads(Class tClass, List<String> exportFieldNames, List<String> notExportFieldNames) {
        //是否全部导出
        boolean allExport = (null != exportFieldNames && !exportFieldNames.isEmpty())?false:true;
        //是否存在不需要导出的属性
        boolean exitsNotExport = (null != notExportFieldNames && !notExportFieldNames.isEmpty())?true:false;
        Field[] fields = tClass.getDeclaredFields();
        Map<String, String> resultMap = new HashMap();
        for (Field field : fields) {
            System.out.println(field.getName());
            // 是否引用Excel注解
            if (field.isAnnotationPresent(Excel.class)) {
                Field f = ExcelPoiUtil.getFieldOfCheck(field, allExport, exitsNotExport, exportFieldNames, notExportFieldNames);
                if (null != f) {
                    resultMap.put(field.getName(), field.getAnnotation(Excel.class).name());
                }
            }
        }
        return resultMap;
    }

    // 检查获取需要的属性
    private static Field getFieldOfCheck(Field field, boolean allExport, boolean exitsNotExport, List<String> exportFieldNames, List<String> notExportFieldNames){
        //全部
        if (allExport) {
            //需要剔除
            if (exitsNotExport) {
                return (!notExportFieldNames.contains(field.getName()))?field:null;
            }
            return field;
        } else {
            if (exitsNotExport) {
                return (!notExportFieldNames.contains(field.getName()) && exportFieldNames.contains(field.getName()))?field:null;
            }
            return (exportFieldNames.contains(field.getName()))?field:null;
        }
    }
}

数据字典实现类DictExcelHandler

import cn.afterturn.easypoi.handler.inter.IExcelDictHandler;
import com.gdgxkj.common.security.model.DictDataModel;
import com.gdgxkj.common.security.utils.DictUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 *@Author: chenlf
 *@CreateTime: 2022-11-28 
 *@Description: 数据字典处理
 *@Version: 1.0
 */
@Component
public class DictExcelHandler implements IExcelDictHandler {


    //导出
    @Override
    public String toName(String dict, Object obj, String value, Object key) {
        return getDictCache(dict, key, null);

    }

    //导入
    @Override
    public String toValue(String dict, Object obj, String value, Object key) {
        return getDictCache(dict, null, value);

    }

    //获取数据字典缓存
    private String getDictCache(String type, Object key, Object value){
        List<DictDataModel> dictCache = DictUtils.getDictCache(type);
        if (null != key) {
            List<DictDataModel> collect = dictCache.stream().filter(item -> item.getDictValue().equals(key)).collect(Collectors.toList());
            if (!collect.isEmpty()) {
                return collect.get(0).getDictLabel();
            }
        }
        if (null != value) {
            List<DictDataModel> collect = dictCache.stream().filter(item -> item.getDictLabel().equals(value)).collect(Collectors.toList());
            if (!collect.isEmpty()) {
                return collect.get(0).getDictValue();
            }
        }
        return StringUtils.EMPTY;
    }
}

使用测试

  • 如果还需要自定义排序,也可以让前端传回来再处理,目前没实现,业务暂时没这个需求
public void export(@RequestBody SearchParam param, HttpServletResponse response) {
        //结果集
        List<TestModel> list = XXService.findList(param);
        try {
            //自定义表头
            //List<ExcelExportEntity> exportEntitys = ExcelPoiUtil.getExportEntitys(new SuggestPOI(), param.getExportFieldNames(), null);
            //测试:导出所有属性
            List<ExcelExportEntity> exportEntitys = ExcelPoiUtil.getExportEntitys(TestModel.class, null, null);

            ExportParams exportParams = new ExportParams();
            exportParams.setDictHandler(new DictExcelHandler());

            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, exportEntitys, result);
            FileOutputStream fos =new FileOutputStream("H:/test.xlsx");
            workbook.write(fos);
            fos.close();
			/*if (workbook != null) {
				response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("XX信息", "UTF-8") + ".xls");
                workbook.write(response.getOutputStream());  
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        }
    }