skyouc
2025-03-13 cbb0dfaec496d441bbf4287ca8ae85c2776e50ed
rsf-server/src/main/java/com/vincent/rsf/server/common/utils/ExcelUtil.java
@@ -1,7 +1,12 @@
package com.vincent.rsf.server.common.utils;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.vincent.rsf.framework.common.Cools;
import com.vincent.rsf.server.manager.entity.excel.annotation.ExcelComment;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
@@ -19,6 +24,7 @@
/**
 * Created by vincent on 2/17/2024
 */
@Slf4j
public class ExcelUtil {
    public static void build(Workbook workbook, HttpServletResponse response) {
@@ -32,6 +38,10 @@
    }
    public static <T> Workbook create(List<T> list, Class<T> clz) {
        return  create(list, clz, false);
    }
    public static <T> Workbook create(List<T> list, Class<T> clz, boolean flagTemplate) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet(clz.getSimpleName());
@@ -45,6 +55,15 @@
                continue;
            }
            String memo = "Undefined";
            if (flagTemplate) {
                if (field.isAnnotationPresent(ExcelComment.class)) {
                    memo = field.getAnnotation(ExcelComment.class).value();
                }
            } else {
                if (field.isAnnotationPresent(Excel.class)) {
                    memo = field.getAnnotation(Excel.class).name();
                }
            }
            if (field.isAnnotationPresent(ApiModelProperty.class)) {
                memo = field.getAnnotation(ApiModelProperty.class).value();
            }
@@ -64,7 +83,8 @@
                    continue;
                }
                field.setAccessible(true);  // 此行很重要,特别是字段为private时
                // 此行很重要,特别是字段为private时
                field.setAccessible(true);
                Object value = null;
                try {
                    value = field.get(t);
@@ -91,76 +111,90 @@
    }
    /**
     * Excel 导入
     * @param file 文件
     * @param keys 数据顺序
     * 添加导入excel配置参数
     * 注:默认配置可满足当前需求
     * @return
     */
    public static  List<Map<String, Object>>  importExcel(MultipartFile file, String[] keys) throws Exception{
        Workbook wb = null;
        String fileName = file.getOriginalFilename();
        if (fileName.endsWith("xls")) {
            POIFSFileSystem pois = new POIFSFileSystem(file.getInputStream());
            wb = new HSSFWorkbook(pois);
        } else if (fileName.endsWith("xlsx")) {
            wb = new XSSFWorkbook(file.getInputStream());
    public static ImportParams getDefaultImportParams() {
        ImportParams params = new ImportParams();
        return params;
    }
    /**
     * 根据 {@code tClass} 相关成员变量的 {@link ExcelComment#example()} 字段创建模拟数据,暂不支持 复杂类型
     * @param tClass
     * @return
     */
    public static <T> T mockData(Class<T> tClass) {
        if (tClass == null) {
            return null;
        }
        Sheet sheet = wb.getSheetAt(0);
        int rowCount = sheet.getPhysicalNumberOfRows();
        if (sheet.getRow( 1).getPhysicalNumberOfCells() != keys.length){
            throw new RuntimeException("导入的Excel和模板的列不匹配");
        }
        List<Map<String,Object>> result = new ArrayList<>();
        for (int i = 0; i < rowCount - 1; i++) {
            Row row = sheet.getRow(i + 1);
            Map<String,Object> tmp = new HashMap<>();
            for (int j = 0;j < keys.length; j++){
                Cell cell = row.getCell(j);
                // 把类型转行String
//                cell.setCellType(CellType.STRING);
                tmp.put(keys[j], cell.getStringCellValue());
        T instance = null;
        try {
            instance = tClass.newInstance();
            Field[] declaredFields = tClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                ExcelComment comment = declaredField.getAnnotation(ExcelComment.class);
                if (comment == null) {
                    continue;
                }
                declaredField.setAccessible(true);
                Class<?> fieldType = declaredField.getType();
                String exampleValue = comment.example();
                Object value = null;
                if (fieldType == int.class || fieldType == Integer.class) {
                    value = StringUtils.isBlank(exampleValue) ? 0 : Integer.parseInt(exampleValue);
                } else if (fieldType == short.class || fieldType == Short.class) {
                    value = StringUtils.isBlank(exampleValue) ? 0 : Short.parseShort(exampleValue);
                } else if (fieldType == long.class || fieldType == Long.class) {
                    value = StringUtils.isBlank(exampleValue) ? 0 : Long.parseLong(exampleValue);
                } else if (fieldType == double.class || fieldType == Double.class) {
                    value = StringUtils.isBlank(exampleValue) ? 0 : Double.parseDouble(exampleValue);
                } else if (fieldType == boolean.class || fieldType == Boolean.class) {
                    value = StringUtils.isNotBlank(exampleValue) && Boolean.parseBoolean(exampleValue);
                } else if (fieldType == String.class) {
                    value = exampleValue;
                } else if (fieldType == Date.class) {
                    value = DateUtils.parse(exampleValue);
                }
                if (value == null && !isBaseType(fieldType)) {
                    declaredField.set(instance, null);
                } else {
                    declaredField.set(instance, value);
                }
            }
            result.add(tmp);
        } catch (Exception e) {
            log.error("数据构造失败,请查询详细信息", e);
            return instance;
        }
        return result;
        return instance;
    }
    /**
     * 表头样式
     */
    private static CellStyle HeaderStyle(Workbook wb){
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 11);
        CellStyle cellStyle = commonStyle(wb);
        cellStyle.setFont(font);
        return cellStyle;
    }
    /**
     * 内容样式
     * 是否是基础数据类型
     *
     * @param className
     * @return
     */
    private static CellStyle contentStyle(Workbook wb){
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 10);
        CellStyle cellStyle = commonStyle(wb);
        cellStyle.setFont(font);
        return cellStyle;
    private static boolean isBaseType(Class<?> className) {
        if (className.equals(java.lang.Integer.class) ||
                className.equals(java.lang.Byte.class) ||
                className.equals(java.lang.Long.class) ||
                className.equals(java.lang.Double.class) ||
                className.equals(java.lang.Float.class) ||
                className.equals(java.lang.Character.class) ||
                className.equals(java.lang.Short.class) ||
                className.equals(java.lang.Boolean.class)) {
            return true;
        }
        return false;
    }
    /**
     * 公共样式
     */
    private static CellStyle commonStyle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setWrapText(true);// 自动换行
        return style;
    }
}