🎉 Initial commit

This commit is contained in:
2026-07-27 14:26:14 +08:00
commit fd54f07889
6935 changed files with 617410 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
package cn.iocoder.yudao.framework.dict.config;
import cn.iocoder.yudao.framework.common.biz.system.dict.DictDataCommonApi;
import cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
@AutoConfiguration
public class YudaoDictAutoConfiguration {
@Bean
@SuppressWarnings("InstantiationOfUtilityClass")
public DictFrameworkUtils dictUtils(DictDataCommonApi dictDataApi) {
DictFrameworkUtils.init(dictDataApi);
return new DictFrameworkUtils();
}
}

View File

@@ -0,0 +1,84 @@
package cn.iocoder.yudao.framework.dict.core;
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.biz.system.dict.DictDataCommonApi;
import cn.iocoder.yudao.framework.common.util.cache.CacheUtils;
import cn.iocoder.yudao.framework.common.biz.system.dict.dto.DictDataRespDTO;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
/**
* 字典工具类
*
* @author 芋道源码
*/
@Slf4j
public class DictFrameworkUtils {
private static DictDataCommonApi dictDataApi;
/**
* 针对 dictType 的字段数据缓存
*/
private static final LoadingCache<String, List<DictDataRespDTO>> GET_DICT_DATA_CACHE = CacheUtils.buildAsyncReloadingCache(
Duration.ofMinutes(1L), // 过期时间 1 分钟
new CacheLoader<String, List<DictDataRespDTO>>() {
@Override
public List<DictDataRespDTO> load(String dictType) {
return dictDataApi.getDictDataList(dictType);
}
});
public static void init(DictDataCommonApi dictDataApi) {
DictFrameworkUtils.dictDataApi = dictDataApi;
log.info("[init][初始化 DictFrameworkUtils 成功]");
}
public static void clearCache() {
GET_DICT_DATA_CACHE.invalidateAll();
}
@SneakyThrows
public static String parseDictDataLabel(String dictType, Integer value) {
if (value == null) {
return null;
}
return parseDictDataLabel(dictType, String.valueOf(value));
}
@SneakyThrows
public static String parseDictDataLabel(String dictType, String value) {
List<DictDataRespDTO> dictDatas = GET_DICT_DATA_CACHE.get(dictType);
DictDataRespDTO dictData = CollUtil.findOne(dictDatas, data -> Objects.equals(data.getValue(), value));
return dictData != null ? dictData.getLabel(): null;
}
@SneakyThrows
public static List<String> getDictDataLabelList(String dictType) {
List<DictDataRespDTO> dictDatas = GET_DICT_DATA_CACHE.get(dictType);
return convertList(dictDatas, DictDataRespDTO::getLabel);
}
@SneakyThrows
public static String parseDictDataValue(String dictType, String label) {
List<DictDataRespDTO> dictDatas = GET_DICT_DATA_CACHE.get(dictType);
DictDataRespDTO dictData = CollUtil.findOne(dictDatas, data -> Objects.equals(data.getLabel(), label));
return dictData!= null ? dictData.getValue(): null;
}
@SneakyThrows
public static List<String> getDictDataValueList(String dictType) {
List<DictDataRespDTO> dictDatas = GET_DICT_DATA_CACHE.get(dictType);
return convertList(dictDatas, DictDataRespDTO::getValue);
}
}

View File

@@ -0,0 +1,6 @@
/**
* 字典数据模块,提供 {@link cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils} 工具类
*
* 通过将字典缓存在内存中,保证性能
*/
package cn.iocoder.yudao.framework.dict;

View File

@@ -0,0 +1,38 @@
package cn.iocoder.yudao.framework.dict.validation;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({
ElementType.METHOD,
ElementType.FIELD,
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.PARAMETER,
ElementType.TYPE_USE
})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
validatedBy = {InDictValidator.class, InDictCollectionValidator.class}
)
public @interface InDict {
/**
* 数据字典 type
*/
String type();
String message() default "必须在指定范围 {value}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

View File

@@ -0,0 +1,43 @@
package cn.iocoder.yudao.framework.dict.validation;
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.Collection;
import java.util.List;
public class InDictCollectionValidator implements ConstraintValidator<InDict, Collection<?>> {
private String dictType;
@Override
public void initialize(InDict annotation) {
this.dictType = annotation.type();
}
@Override
public boolean isValid(Collection<?> list, ConstraintValidatorContext context) {
// 为空时,默认不校验,即认为通过
if (CollUtil.isEmpty(list)) {
return true;
}
// 校验全部通过
List<String> dbValues = DictFrameworkUtils.getDictDataValueList(dictType);
boolean match = list.stream().allMatch(v -> dbValues.stream()
.anyMatch(dbValue -> dbValue.equalsIgnoreCase(v.toString())));
if (match) {
return true;
}
// 校验不通过,自定义提示语句
context.disableDefaultConstraintViolation(); // 禁用默认的 message 的值
context.buildConstraintViolationWithTemplate(
context.getDefaultConstraintMessageTemplate().replaceAll("\\{value}", dbValues.toString())
).addConstraintViolation(); // 重新添加错误提示语句
return false;
}
}

View File

@@ -0,0 +1,41 @@
package cn.iocoder.yudao.framework.dict.validation;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.List;
public class InDictValidator implements ConstraintValidator<InDict, Object> {
private String dictType;
@Override
public void initialize(InDict annotation) {
this.dictType = annotation.type();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
// 为空时,默认不校验,即认为通过
if (value == null) {
return true;
}
// 校验通过
final List<String> values = DictFrameworkUtils.getDictDataValueList(dictType);
boolean match = values.stream().anyMatch(v -> StrUtil.equalsIgnoreCase(v, value.toString()));
if (match) {
return true;
}
// 校验不通过,自定义提示语句
context.disableDefaultConstraintViolation(); // 禁用默认的 message 的值
context.buildConstraintViolationWithTemplate(
context.getDefaultConstraintMessageTemplate().replaceAll("\\{value}", values.toString())
).addConstraintViolation(); // 重新添加错误提示语句
return false;
}
}

View File

@@ -0,0 +1,22 @@
package cn.iocoder.yudao.framework.excel.core.annotations;
import java.lang.annotation.*;
/**
* 字典格式化
*
* 实现将字典数据的值,格式化成字典数据的标签
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface DictFormat {
/**
* 例如说SysDictTypeConstants、InfDictTypeConstants
*
* @return 字典类型
*/
String value();
}

View File

@@ -0,0 +1,27 @@
package cn.iocoder.yudao.framework.excel.core.annotations;
import java.lang.annotation.*;
/**
* 给 Excel 列添加下拉选择数据
*
* 其中 {@link #dictType()} 和 {@link #functionName()} 二选一
*
* @author HUIHUI
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ExcelColumnSelect {
/**
* @return 字典类型
*/
String dictType() default "";
/**
* @return 获取下拉数据源的方法名称
*/
String functionName() default "";
}

View File

@@ -0,0 +1,46 @@
package cn.iocoder.yudao.framework.excel.core.convert;
import cn.hutool.core.convert.Convert;
import cn.iocoder.yudao.framework.ip.core.Area;
import cn.iocoder.yudao.framework.ip.core.utils.AreaUtils;
import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;
import lombok.extern.slf4j.Slf4j;
/**
* Excel 数据地区转换器
*
* @author HUIHUI
*/
@Slf4j
public class AreaConvert implements Converter<Object> {
@Override
public Class<?> supportJavaTypeKey() {
throw new UnsupportedOperationException("暂不支持,也不需要");
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
throw new UnsupportedOperationException("暂不支持,也不需要");
}
@Override
public Object convertToJavaData(ReadCellData readCellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
// 解析地区编号
String label = readCellData.getStringValue();
Area area = AreaUtils.parseArea(label);
if (area == null) {
log.error("[convertToJavaData][label({}) 解析不掉]", label);
return null;
}
// 将 value 转换成对应的属性
Class<?> fieldClazz = contentProperty.getField().getType();
return Convert.convert(fieldClazz, area.getId());
}
}

View File

@@ -0,0 +1,72 @@
package cn.iocoder.yudao.framework.excel.core.convert;
import cn.hutool.core.convert.Convert;
import cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils;
import cn.iocoder.yudao.framework.excel.core.annotations.DictFormat;
import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;
import lombok.extern.slf4j.Slf4j;
/**
* Excel 数据字典转换器
*
* @author 芋道源码
*/
@Slf4j
public class DictConvert implements Converter<Object> {
@Override
public Class<?> supportJavaTypeKey() {
throw new UnsupportedOperationException("暂不支持,也不需要");
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
throw new UnsupportedOperationException("暂不支持,也不需要");
}
@Override
public Object convertToJavaData(ReadCellData readCellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
// 使用字典解析
String type = getType(contentProperty);
String label = readCellData.getStringValue();
String value = DictFrameworkUtils.parseDictDataValue(type, label);
if (value == null) {
log.error("[convertToJavaData][type({}) 解析不掉 label({})]", type, label);
return null;
}
// 将 String 的 value 转换成对应的属性
Class<?> fieldClazz = contentProperty.getField().getType();
return Convert.convert(fieldClazz, value);
}
@Override
public WriteCellData<String> convertToExcelData(Object object, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
// 空时,返回空
if (object == null) {
return new WriteCellData<>("");
}
// 使用字典格式化
String type = getType(contentProperty);
String value = String.valueOf(object);
String label = DictFrameworkUtils.parseDictDataLabel(type, value);
if (label == null) {
log.error("[convertToExcelData][type({}) 转换不了 label({})]", type, value);
return new WriteCellData<>("");
}
// 生成 Excel 小表格
return new WriteCellData<>(label);
}
private static String getType(ExcelContentProperty contentProperty) {
return contentProperty.getField().getAnnotation(DictFormat.class).value();
}
}

View File

@@ -0,0 +1,34 @@
package cn.iocoder.yudao.framework.excel.core.convert;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;
/**
* Excel Json 转换器
*
* @author 芋道源码
*/
public class JsonConvert implements Converter<Object> {
@Override
public Class<?> supportJavaTypeKey() {
throw new UnsupportedOperationException("暂不支持,也不需要");
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
throw new UnsupportedOperationException("暂不支持,也不需要");
}
@Override
public WriteCellData<String> convertToExcelData(Object value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
// 生成 Excel 小表格
return new WriteCellData<>(JsonUtils.toJsonString(value));
}
}

View File

@@ -0,0 +1,39 @@
package cn.iocoder.yudao.framework.excel.core.convert;
import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* 金额转换器
*
* 金额单位:分
*
* @author 芋道源码
*/
public class MoneyConvert implements Converter<Integer> {
@Override
public Class<?> supportJavaTypeKey() {
throw new UnsupportedOperationException("暂不支持,也不需要");
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
throw new UnsupportedOperationException("暂不支持,也不需要");
}
@Override
public WriteCellData<String> convertToExcelData(Integer value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
BigDecimal result = BigDecimal.valueOf(value)
.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
return new WriteCellData<>(result.toString());
}
}

View File

@@ -0,0 +1,207 @@
package cn.iocoder.yudao.framework.excel.core.convert;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils;
import cn.iocoder.yudao.framework.excel.core.annotations.DictFormat;
import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Excel 多值数据字典转换器
*
* 数据库存储值使用半角逗号分隔,例如 {@code 1,2}
* Excel 展示使用顿号分隔,例如 {@code 男、女}
* 使用时,需要在字段上同时配置
* {@code @ExcelProperty(converter = MultiDictConvert.class)} 和 {@link DictFormat}
*
* @author NaCl
*/
@Slf4j
public class MultiDictConvert implements Converter<Object> {
private static final String EXCEL_SEPARATOR = "";
private static final String DB_SEPARATOR = ",";
private static final String EXCEL_SEPARATOR_REGEX = "[、,]";
@Override
public Class<?> supportJavaTypeKey() {
throw new UnsupportedOperationException("暂不支持,也不需要");
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
throw new UnsupportedOperationException("暂不支持,也不需要");
}
@Override
public Object convertToJavaData(ReadCellData readCellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
// 空时,返回空值
Field field = contentProperty.getField();
String labels = readCellData.getStringValue();
if (StrUtil.isBlank(labels)) {
return convertToFieldValue(field, new ArrayList<>());
}
// 使用字典解析
String type = getType(contentProperty);
String[] labelArray = labels.split(EXCEL_SEPARATOR_REGEX);
List<String> values = new ArrayList<>(labelArray.length);
for (String item : labelArray) {
String label = item.trim();
if (StrUtil.isBlank(label)) {
continue;
}
String value = DictFrameworkUtils.parseDictDataValue(type, label);
if (value == null) {
log.error("[convertToJavaData][type({}) 解析不掉 label({})]", type, label);
return null;
}
values.add(value);
}
// 将 String 的 value 转换成对应的属性
return convertToFieldValue(field, values);
}
@Override
public WriteCellData<String> convertToExcelData(Object object, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
// 空时,返回空
if (object == null) {
return new WriteCellData<>("");
}
// 使用字典格式化
String type = getType(contentProperty);
List<String> values = convertToStringList(object);
List<String> labels = new ArrayList<>(values.size());
for (String value : values) {
String label = DictFrameworkUtils.parseDictDataLabel(type, value);
if (label == null) {
log.error("[convertToExcelData][type({}) 转换不了 value({})]", type, value);
return new WriteCellData<>("");
}
labels.add(label);
}
// 生成 Excel 小表格
return new WriteCellData<>(String.join(EXCEL_SEPARATOR, labels));
}
private static Object convertToFieldValue(Field field, List<String> values) {
Class<?> fieldClazz = field.getType();
if (String.class == fieldClazz) {
return String.join(DB_SEPARATOR, values);
}
if (fieldClazz.isArray()) {
return convertToArray(fieldClazz.getComponentType(), values);
}
if (Collection.class.isAssignableFrom(fieldClazz)) {
return convertToCollection(field, values);
}
return Convert.convert(fieldClazz, String.join(DB_SEPARATOR, values));
}
private static Object convertToArray(Class<?> componentType, List<String> values) {
Object array = Array.newInstance(componentType, values.size());
for (int i = 0; i < values.size(); i++) {
Array.set(array, i, Convert.convert(componentType, values.get(i)));
}
return array;
}
private static Collection<?> convertToCollection(Field field, List<String> values) {
Class<?> elementClazz = getCollectionElementClazz(field);
Collection<Object> result = createCollection(field.getType());
for (String value : values) {
result.add(Convert.convert(elementClazz, value));
}
return result;
}
@SuppressWarnings("unchecked")
private static Collection<Object> createCollection(Class<?> fieldClazz) {
if (!fieldClazz.isInterface() && !Modifier.isAbstract(fieldClazz.getModifiers())) {
try {
return (Collection<Object>) fieldClazz.getDeclaredConstructor().newInstance();
} catch (Exception ignored) {
// 使用默认集合实现
}
}
return Set.class.isAssignableFrom(fieldClazz) ? new LinkedHashSet<>() : new ArrayList<>();
}
private static Class<?> getCollectionElementClazz(Field field) {
Type genericType = field.getGenericType();
if (!(genericType instanceof ParameterizedType)) {
return String.class;
}
Type actualType = ((ParameterizedType) genericType).getActualTypeArguments()[0];
if (actualType instanceof Class<?>) {
return (Class<?>) actualType;
}
if (actualType instanceof ParameterizedType
&& ((ParameterizedType) actualType).getRawType() instanceof Class<?>) {
return (Class<?>) ((ParameterizedType) actualType).getRawType();
}
return String.class;
}
private static List<String> convertToStringList(Object object) {
List<String> values = new ArrayList<>();
if (object instanceof String) {
String[] valueArray = ((String) object).split(DB_SEPARATOR);
for (String value : valueArray) {
addStringValue(values, value);
}
return values;
}
if (object instanceof Collection<?>) {
for (Object item : (Collection<?>) object) {
addStringValue(values, item);
}
return values;
}
if (object.getClass().isArray()) {
int length = Array.getLength(object);
for (int i = 0; i < length; i++) {
addStringValue(values, Array.get(object, i));
}
return values;
}
addStringValue(values, object);
return values;
}
private static void addStringValue(List<String> values, Object value) {
if (value == null) {
return;
}
String str = String.valueOf(value).trim();
if (StrUtil.isBlank(str)) {
return;
}
values.add(str);
}
private static String getType(ExcelContentProperty contentProperty) {
return contentProperty.getField().getAnnotation(DictFormat.class).value();
}
}

View File

@@ -0,0 +1,28 @@
package cn.iocoder.yudao.framework.excel.core.function;
import java.util.List;
/**
* Excel 列下拉数据源获取接口
*
* 为什么不直接解析字典还搞个接口?考虑到有的下拉数据不是从字典中获取的所有需要做一个兼容
* @author HUIHUI
*/
public interface ExcelColumnSelectFunction {
/**
* 获得方法名称
*
* @return 方法名称
*/
String getName();
/**
* 获得列下拉数据源
*
* @return 下拉数据源
*/
List<String> getOptions();
}

View File

@@ -0,0 +1,78 @@
package cn.iocoder.yudao.framework.excel.core.handler;
import cn.hutool.core.collection.CollUtil;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.Head;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.util.MapUtils;
import cn.idev.excel.write.metadata.holder.WriteSheetHolder;
import cn.idev.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import cn.idev.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Excel 自适应列宽处理器
*
* 相比 {@link LongestMatchColumnWidthStyleStrategy} 来说,额外处理了 DATE 类型!
*
* @see <a href="https://github.com/YunaiV/yudao-cloud/pull/196/">添加自适应列宽处理器,并替换默认列宽策略</a>
* @author hmb
*/
public class ColumnWidthMatchStyleStrategy extends AbstractColumnWidthStyleStrategy {
private static final int MAX_COLUMN_WIDTH = 255;
private final Map<Integer, Map<Integer, Integer>> cache = MapUtils.newHashMapWithExpectedSize(8);
@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell,
Head head, Integer relativeRowIndex, Boolean isHead) {
boolean needSetWidth = isHead || CollUtil.isNotEmpty(cellDataList);
if (!needSetWidth) {
return;
}
Map<Integer, Integer> maxColumnWidthMap = cache.computeIfAbsent(writeSheetHolder.getSheetNo(),
key -> new HashMap<>(16));
Integer columnWidth = dataLength(cellDataList, cell, isHead);
if (columnWidth < 0) {
return;
}
if (columnWidth > MAX_COLUMN_WIDTH) {
columnWidth = MAX_COLUMN_WIDTH;
}
Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
}
}
@SuppressWarnings("EnhancedSwitchMigration")
private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {
if (isHead) {
return cell.getStringCellValue().getBytes().length;
}
WriteCellData<?> cellData = cellDataList.get(0);
CellDataTypeEnum type = cellData.getType();
if (type == null) {
return -1;
}
switch (type) {
case STRING:
return cellData.getStringValue().getBytes().length;
case BOOLEAN:
return cellData.getBooleanValue().toString().getBytes().length;
case NUMBER:
return cellData.getNumberValue().toString().getBytes().length;
case DATE:
return cellData.getDateValue().toString().getBytes().length;
default:
return -1;
}
}
}

View File

@@ -0,0 +1,187 @@
package cn.iocoder.yudao.framework.excel.core.handler;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.iocoder.yudao.framework.common.core.KeyValue;
import cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils;
import cn.iocoder.yudao.framework.excel.core.annotations.ExcelColumnSelect;
import cn.iocoder.yudao.framework.excel.core.function.ExcelColumnSelectFunction;
import cn.idev.excel.annotation.ExcelIgnore;
import cn.idev.excel.annotation.ExcelIgnoreUnannotated;
import cn.idev.excel.annotation.ExcelProperty;
import cn.idev.excel.write.handler.SheetWriteHandler;
import cn.idev.excel.write.metadata.holder.WriteSheetHolder;
import cn.idev.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
/**
* 基于固定 sheet 实现下拉框
*
* @author HUIHUI
*/
@Slf4j
public class SelectSheetWriteHandler implements SheetWriteHandler {
/**
* 数据起始行从 0 开始
*
* 约定:本项目第一行有标题所以从 1 开始如果您的 Excel 有多行标题请自行更改
*/
public static final int FIRST_ROW = 1;
/**
* 下拉列需要创建下拉框的行数,默认两千行如需更多请自行调整
*/
public static final int LAST_ROW = 2000;
private static final String DICT_SHEET_NAME = "字典sheet";
/**
* key: 列 value: 下拉数据源
*/
private final Map<Integer, List<String>> selectMap = new HashMap<>();
public SelectSheetWriteHandler(Class<?> head) {
// 解析下拉数据
int colIndex = 0;
boolean ignoreUnannotated = head.isAnnotationPresent(ExcelIgnoreUnannotated.class);
for (Field field : head.getDeclaredFields()) {
// 关联 https://github.com/YunaiV/ruoyi-vue-pro/pull/853
// 1.1 忽略 static final 或 transient 的字段
if (isStaticFinalOrTransient(field) ) {
continue;
}
// 1.2 忽略的字段跳过
if ((ignoreUnannotated && !field.isAnnotationPresent(ExcelProperty.class))
|| field.isAnnotationPresent(ExcelIgnore.class)) {
continue;
}
// 2. 核心:处理有 ExcelColumnSelect 注解的字段
if (field.isAnnotationPresent(ExcelColumnSelect.class)) {
ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
if (excelProperty != null && excelProperty.index() != -1) {
colIndex = excelProperty.index();
}
getSelectDataList(colIndex, field);
}
colIndex++;
}
}
/**
* 判断字段是否是静态的、最终的、 transient 的
* 原因FastExcel 默认是忽略 static final 或 transient 的字段,所以需要判断
*
* @param field 字段
* @return 是否是静态的、最终的、transient 的
*/
private boolean isStaticFinalOrTransient(Field field) {
return (Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers()))
|| Modifier.isTransient(field.getModifiers());
}
/**
* 获得下拉数据,并添加到 {@link #selectMap} 中
*
* @param colIndex 列索引
* @param field 字段
*/
private void getSelectDataList(int colIndex, Field field) {
ExcelColumnSelect columnSelect = field.getAnnotation(ExcelColumnSelect.class);
String dictType = columnSelect.dictType();
String functionName = columnSelect.functionName();
Assert.isTrue(ObjectUtil.isNotEmpty(dictType) || ObjectUtil.isNotEmpty(functionName),
"Field({}) 的 @ExcelColumnSelect 注解dictType 和 functionName 不能同时为空", field.getName());
// 情况一:使用 dictType 获得下拉数据
if (StrUtil.isNotEmpty(dictType)) { // 情况一: 字典数据 (默认)
selectMap.put(colIndex, DictFrameworkUtils.getDictDataLabelList(dictType));
return;
}
// 情况二:使用 functionName 获得下拉数据
Map<String, ExcelColumnSelectFunction> functionMap = SpringUtil.getApplicationContext().getBeansOfType(ExcelColumnSelectFunction.class);
ExcelColumnSelectFunction function = CollUtil.findOne(functionMap.values(), item -> item.getName().equals(functionName));
Assert.notNull(function, "未找到对应的 function({})", functionName);
selectMap.put(colIndex, function.getOptions());
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
if (CollUtil.isEmpty(selectMap)) {
return;
}
// 1. 获取相应操作对象
DataValidationHelper helper = writeSheetHolder.getSheet().getDataValidationHelper(); // 需要设置下拉框的 sheet 页的数据验证助手
Workbook workbook = writeWorkbookHolder.getWorkbook(); // 获得工作簿
List<KeyValue<Integer, List<String>>> keyValues = convertList(selectMap.entrySet(), entry -> new KeyValue<>(entry.getKey(), entry.getValue()));
keyValues.sort(Comparator.comparing(item -> item.getValue().size())); // 升序不然创建下拉会报错
// 2. 创建数据字典的 sheet 页
Sheet dictSheet = workbook.createSheet(DICT_SHEET_NAME);
for (KeyValue<Integer, List<String>> keyValue : keyValues) {
int rowLength = keyValue.getValue().size();
// 2.1 设置字典 sheet 页的值,每一列一个字典项
for (int i = 0; i < rowLength; i++) {
Row row = dictSheet.getRow(i);
if (row == null) {
row = dictSheet.createRow(i);
}
row.createCell(keyValue.getKey()).setCellValue(keyValue.getValue().get(i));
}
// 2.2 设置单元格下拉选择
setColumnSelect(writeSheetHolder, workbook, helper, keyValue);
}
}
/**
* 设置单元格下拉选择
*/
private static void setColumnSelect(WriteSheetHolder writeSheetHolder, Workbook workbook, DataValidationHelper helper,
KeyValue<Integer, List<String>> keyValue) {
// 1.1 创建可被其他单元格引用的名称
Name name = workbook.createName();
String excelColumn = ExcelUtil.indexToColName(keyValue.getKey());
// 1.2 下拉框数据来源 eg:字典sheet!$B1:$B2
String refers = DICT_SHEET_NAME + "!$" + excelColumn + "$1:$" + excelColumn + "$" + keyValue.getValue().size();
name.setNameName("dict" + keyValue.getKey()); // 设置名称的名字
name.setRefersToFormula(refers); // 设置公式
// 2.1 设置约束
DataValidationConstraint constraint = helper.createFormulaListConstraint("dict" + keyValue.getKey()); // 设置引用约束
// 设置下拉单元格的首行、末行、首列、末列
CellRangeAddressList rangeAddressList = new CellRangeAddressList(FIRST_ROW, LAST_ROW,
keyValue.getKey(), keyValue.getKey());
DataValidation validation = helper.createValidation(constraint, rangeAddressList);
if (validation instanceof HSSFDataValidation) {
validation.setSuppressDropDownArrow(false);
} else {
validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true);
}
// 2.2 阻止输入非下拉框的值
validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
validation.createErrorBox("提示", "此值不存在于下拉选择中!");
// 2.3 添加下拉框约束
writeSheetHolder.getSheet().addValidationData(validation);
}
}

View File

@@ -0,0 +1,56 @@
package cn.iocoder.yudao.framework.excel.core.util;
import cn.idev.excel.FastExcelFactory;
import cn.idev.excel.converters.longconverter.LongStringConverter;
import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.framework.excel.core.handler.ColumnWidthMatchStyleStrategy;
import cn.iocoder.yudao.framework.excel.core.handler.SelectSheetWriteHandler;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* Excel 工具类
*
* @author 芋道源码
*/
public class ExcelUtils {
/**
* 将列表以 Excel 响应给前端
*
* @param response 响应
* @param filename 文件名
* @param sheetName Excel sheet 名
* @param head Excel head 头
* @param data 数据列表哦
* @param <T> 泛型,保证 head 和 data 类型的一致性
* @throws IOException 写入失败的情况
*/
public static <T> void write(HttpServletResponse response, String filename, String sheetName,
Class<T> head, List<T> data) throws IOException {
// 输出 Excel
FastExcelFactory.write(response.getOutputStream(), head)
.autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
.registerWriteHandler(new ColumnWidthMatchStyleStrategy()) // 基于 column 长度,自动适配。最大 255 宽度
.registerWriteHandler(new SelectSheetWriteHandler(head)) // 基于固定 sheet 实现下拉框
.registerConverter(new LongStringConverter()) // 避免 Long 类型丢失精度
.sheet(sheetName).doWrite(data);
// 设置 header 和 contentType。写在最后的原因是避免报错时响应 contentType 已经被修改了
response.addHeader("Content-Disposition", "attachment;filename=" + HttpUtils.encodeUtf8(filename));
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
}
public static <T> List<T> read(MultipartFile file, Class<T> head) throws IOException {
// 参考 https://t.zsxq.com/zM77F 帖子,增加 try 处理,兼容 windows 场景
try (InputStream inputStream = file.getInputStream()) {
return FastExcelFactory.read(inputStream, head, null)
.autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
.doReadAllSync();
}
}
}

View File

@@ -0,0 +1,4 @@
/**
* 基于 FastExcel 实现 Excel 相关的操作
*/
package cn.iocoder.yudao.framework.excel;

View File

@@ -0,0 +1 @@
cn.iocoder.yudao.framework.dict.config.YudaoDictAutoConfiguration

View File

@@ -0,0 +1,61 @@
package cn.iocoder.yudao.framework.dict.core.util;
import cn.hutool.core.collection.ListUtil;
import cn.iocoder.yudao.framework.common.biz.system.dict.DictDataCommonApi;
import cn.iocoder.yudao.framework.common.biz.system.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils;
import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import java.util.List;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
/**
* {@link DictFrameworkUtils} 的单元测试
*/
public class DictFrameworkUtilsTest extends BaseMockitoUnitTest {
@Mock
private DictDataCommonApi dictDataApi;
@BeforeEach
public void setUp() {
DictFrameworkUtils.init(dictDataApi);
DictFrameworkUtils.clearCache();
}
@Test
public void testParseDictDataLabel() {
// mock 数据
List<DictDataRespDTO> dictDatas = ListUtil.of(
randomPojo(DictDataRespDTO.class, o -> o.setDictType("animal").setValue("cat").setLabel("")),
randomPojo(DictDataRespDTO.class, o -> o.setDictType("animal").setValue("dog").setLabel(""))
);
// mock 方法
when(dictDataApi.getDictDataList(eq("animal"))).thenReturn(dictDatas);
// 断言返回值
assertEquals("", DictFrameworkUtils.parseDictDataLabel("animal", "dog"));
}
@Test
public void testParseDictDataValue() {
// mock 数据
List<DictDataRespDTO> dictDatas = ListUtil.of(
randomPojo(DictDataRespDTO.class, o -> o.setDictType("animal").setValue("cat").setLabel("")),
randomPojo(DictDataRespDTO.class, o -> o.setDictType("animal").setValue("dog").setLabel(""))
);
// mock 方法
when(dictDataApi.getDictDataList(eq("animal"))).thenReturn(dictDatas);
// 断言返回值
assertEquals("dog", DictFrameworkUtils.parseDictDataValue("animal", ""));
}
}

View File

@@ -0,0 +1,295 @@
package cn.iocoder.yudao.framework.excel.core.convert;
import cn.hutool.core.collection.ListUtil;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;
import cn.iocoder.yudao.framework.common.biz.system.dict.DictDataCommonApi;
import cn.iocoder.yudao.framework.common.biz.system.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils;
import cn.iocoder.yudao.framework.excel.core.annotations.DictFormat;
import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* {@link MultiDictConvert} 的单元测试
*
* @author NaCl
*/
public class MultiDictConvertTest extends BaseMockitoUnitTest {
private static final String DICT_TYPE = "test_dict";
@Mock
private DictDataCommonApi dictDataApi;
private MultiDictConvert convert;
@BeforeEach
public void setUp() {
convert = new MultiDictConvert();
DictFrameworkUtils.init(dictDataApi);
DictFrameworkUtils.clearCache();
}
@Test
public void testConvertToExcelData_string() throws NoSuchFieldException {
// mock 数据
mockDictDatas();
// 调用
WriteCellData<String> result = convert.convertToExcelData("1,2", mockContentProperty("stringValues"), null);
// 断言
assertEquals("男、女", result.getStringValue());
}
@Test
public void testConvertToExcelData_single() throws NoSuchFieldException {
// mock 数据
mockDictDatas();
// 调用
WriteCellData<String> result = convert.convertToExcelData("1", mockContentProperty("stringValues"), null);
// 断言
assertEquals("", result.getStringValue());
}
@Test
public void testConvertToExcelData_order() throws NoSuchFieldException {
// mock 数据
mockDictDatas();
// 调用
WriteCellData<String> result = convert.convertToExcelData("2,1", mockContentProperty("stringValues"), null);
// 断言
assertEquals("女、男", result.getStringValue());
}
@Test
public void testConvertToExcelData_null() {
// 调用
WriteCellData<String> result = convert.convertToExcelData(null, null, null);
// 断言
assertEquals("", result.getStringValue());
}
@Test
public void testConvertToExcelData_collection() throws NoSuchFieldException {
// mock 数据
mockDictDatas();
// 调用
WriteCellData<String> result = convert.convertToExcelData(ListUtil.of(1, 2),
mockContentProperty("listValues"), null);
// 断言
assertEquals("男、女", result.getStringValue());
}
@Test
public void testConvertToExcelData_array() throws NoSuchFieldException {
// mock 数据
mockDictDatas();
// 调用
WriteCellData<String> result = convert.convertToExcelData(new int[]{1, 2},
mockContentProperty("stringValues"), null);
// 断言
assertEquals("男、女", result.getStringValue());
}
@Test
public void testConvertToExcelData_unknownValue() throws NoSuchFieldException {
// mock 数据
mockDictDatas();
// 调用
WriteCellData<String> result = convert.convertToExcelData("1,3", mockContentProperty("stringValues"), null);
// 断言
assertEquals("", result.getStringValue());
}
@Test
public void testConvertToJavaData_string() throws NoSuchFieldException {
// mock 数据
mockDictDatas();
// 调用
Object result = convert.convertToJavaData(mockReadCellData("男、女"),
mockContentProperty("stringValues"), null);
// 断言
assertEquals("1,2", result);
}
@Test
public void testConvertToJavaData_single() throws NoSuchFieldException {
// mock 数据
mockDictDatas();
// 调用
Object result = convert.convertToJavaData(mockReadCellData(""),
mockContentProperty("stringValues"), null);
// 断言
assertEquals("1", result);
}
@Test
public void testConvertToJavaData_blank() throws NoSuchFieldException {
// 调用
Object result = convert.convertToJavaData(mockReadCellData(""),
mockContentProperty("stringValues"), null);
// 断言
assertEquals("", result);
}
@Test
public void testConvertToJavaData_blankList() throws NoSuchFieldException {
// 调用
Object result = convert.convertToJavaData(mockReadCellData(""),
mockContentProperty("listValues"), null);
// 断言
assertTrue(result instanceof List);
assertTrue(((List<?>) result).isEmpty());
}
@Test
public void testConvertToJavaData_blankSet() throws NoSuchFieldException {
// 调用
Object result = convert.convertToJavaData(mockReadCellData(""),
mockContentProperty("setValues"), null);
// 断言
assertTrue(result instanceof LinkedHashSet);
assertTrue(((Set<?>) result).isEmpty());
}
@Test
public void testConvertToJavaData_blankArray() throws NoSuchFieldException {
// 调用
Object result = convert.convertToJavaData(mockReadCellData(""),
mockContentProperty("arrayValues"), null);
// 断言
assertArrayEquals(new Integer[0], (Integer[]) result);
}
@Test
@SuppressWarnings("unchecked")
public void testConvertToJavaData_list() throws NoSuchFieldException {
// mock 数据
mockDictDatas();
// 调用
Object result = convert.convertToJavaData(mockReadCellData("男、女"),
mockContentProperty("listValues"), null);
// 断言
assertEquals(ListUtil.of(1, 2), (List<Integer>) result);
}
@Test
@SuppressWarnings("unchecked")
public void testConvertToJavaData_set() throws NoSuchFieldException {
// mock 数据
mockDictDatas();
// 调用
Object result = convert.convertToJavaData(mockReadCellData("男,女"),
mockContentProperty("setValues"), null);
// 断言
assertEquals(new LinkedHashSet<>(Arrays.asList(1L, 2L)), (Set<Long>) result);
}
@Test
@SuppressWarnings("SimplifiableAssertion")
public void testConvertToJavaData_hashSet() throws NoSuchFieldException {
// mock 数据
mockDictDatas();
// 调用
Object result = convert.convertToJavaData(mockReadCellData("男,女"),
mockContentProperty("hashSetValues"), null);
// 断言
assertTrue(result instanceof HashSet);
assertEquals(new HashSet<>(Arrays.asList(1L, 2L)), result);
}
@Test
public void testConvertToJavaData_array() throws NoSuchFieldException {
// mock 数据
mockDictDatas();
// 调用
Object result = convert.convertToJavaData(mockReadCellData("男,女"),
mockContentProperty("arrayValues"), null);
// 断言
assertArrayEquals(new Integer[]{1, 2}, (Integer[]) result);
}
@Test
public void testConvertToJavaData_unknownLabel() throws NoSuchFieldException {
// mock 数据
mockDictDatas();
// 调用
Object result = convert.convertToJavaData(mockReadCellData("男、未知"),
mockContentProperty("stringValues"), null);
// 断言
assertNull(result);
}
private void mockDictDatas() {
List<DictDataRespDTO> dictDatas = ListUtil.of(
randomPojo(DictDataRespDTO.class, o -> o.setDictType(DICT_TYPE).setValue("1").setLabel("")),
randomPojo(DictDataRespDTO.class, o -> o.setDictType(DICT_TYPE).setValue("2").setLabel(""))
);
when(dictDataApi.getDictDataList(eq(DICT_TYPE))).thenReturn(dictDatas);
}
private static ReadCellData<?> mockReadCellData(String value) {
ReadCellData<?> readCellData = mock(ReadCellData.class);
when(readCellData.getStringValue()).thenReturn(value);
return readCellData;
}
private static ExcelContentProperty mockContentProperty(String fieldName) throws NoSuchFieldException {
Field field = TestExcelVO.class.getDeclaredField(fieldName);
ExcelContentProperty contentProperty = mock(ExcelContentProperty.class);
when(contentProperty.getField()).thenReturn(field);
return contentProperty;
}
static class TestExcelVO {
@DictFormat(DICT_TYPE)
private String stringValues;
@DictFormat(DICT_TYPE)
private List<Integer> listValues;
@DictFormat(DICT_TYPE)
private Set<Long> setValues;
@DictFormat(DICT_TYPE)
private HashSet<Long> hashSetValues;
@DictFormat(DICT_TYPE)
private Integer[] arrayValues;
}
}