Skip to content

Commit

Permalink
feat(字典): 自动字典转换
Browse files Browse the repository at this point in the history
Closes 41
  • Loading branch information
lltx committed Aug 30, 2024
1 parent 97b239c commit 259fc4a
Show file tree
Hide file tree
Showing 17 changed files with 790 additions and 47 deletions.
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,49 @@ public List<DemoData> export(String param) {
return list;
}
```
### 字典转换

- 方式一: 固定枚举

```java
@ExcelProperty(value = "列1")
// 指定对应的枚举类 (字符串)
@DictTypeProperty(enums = SexEnum.class)
private String sex;
```

```java
@Getter
@RequiredArgsConstructor
// 必须继承 DictEnum
public enum SexEnum implements DictEnum {
MALE("0", ""),
FEMALE("1", "");
// 必须有的字段
private final String value;
// 必须有的字段
private final String label;
}
```

- 方式二: 读取系统字典

```java
@Autowired
private DictDataProvider dictDataProvider;

// 在系统启动完毕后,添加字典数据
dictDataProvider.addDict("sex_type", "0", "");
dictDataProvider.addDict("sex_type", "1", "");
```

```java
@ExcelProperty(value = "列1")
// 指定对应的字典类型
@DictTypeProperty("sex_type")
private String sex;
```


### 导出并加密

Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
</parent>
<groupId>com.pig4cloud.excel</groupId>
<artifactId>excel-spring-boot-starter</artifactId>
<version>3.3.0</version>
<version>3.3.1-SNAPSHOT</version>
<name>excel-spring-boot-starter</name>
<description>easy and high performance excel</description>
<url>https://pig4cloud.com</url>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import com.pig4cloud.plugin.excel.aop.RequestExcelArgumentResolver;
import com.pig4cloud.plugin.excel.aop.ResponseExcelReturnValueHandler;
import com.pig4cloud.plugin.excel.config.ExcelConfigProperties;
import com.pig4cloud.plugin.excel.handler.DefaultDictDataProvider;
import com.pig4cloud.plugin.excel.handler.DictDataProvider;
import com.pig4cloud.plugin.excel.kit.SpringContextKit;
import com.pig4cloud.plugin.excel.processor.NameProcessor;
import com.pig4cloud.plugin.excel.processor.NameSpelExpressionProcessor;
import jakarta.annotation.PostConstruct;
Expand All @@ -28,60 +31,67 @@
*/
@AutoConfiguration
@RequiredArgsConstructor
@Import(ExcelHandlerConfiguration.class)
@Import({ExcelHandlerConfiguration.class, SpringContextKit.class})
@EnableConfigurationProperties(ExcelConfigProperties.class)
public class ResponseExcelAutoConfiguration {

private final RequestMappingHandlerAdapter requestMappingHandlerAdapter;
private final RequestMappingHandlerAdapter requestMappingHandlerAdapter;

private final ResponseExcelReturnValueHandler responseExcelReturnValueHandler;
private final ResponseExcelReturnValueHandler responseExcelReturnValueHandler;

/**
* SPEL 解析处理器
* @return NameProcessor excel名称解析器
*/
@Bean
@ConditionalOnMissingBean
public NameProcessor nameProcessor() {
return new NameSpelExpressionProcessor();
}
/**
* SPEL 解析处理器
*
* @return NameProcessor excel名称解析器
*/
@Bean
@ConditionalOnMissingBean
public NameProcessor nameProcessor() {
return new NameSpelExpressionProcessor();
}

/**
* Excel名称解析处理切面
* @param nameProcessor SPEL 解析处理器
* @return DynamicNameAspect
*/
@Bean
@ConditionalOnMissingBean
public DynamicNameAspect dynamicNameAspect(NameProcessor nameProcessor) {
return new DynamicNameAspect(nameProcessor);
}
/**
* Excel名称解析处理切面
*
* @param nameProcessor SPEL 解析处理器
* @return DynamicNameAspect
*/
@Bean
@ConditionalOnMissingBean
public DynamicNameAspect dynamicNameAspect(NameProcessor nameProcessor) {
return new DynamicNameAspect(nameProcessor);
}

/**
* 追加 Excel返回值处理器 到 springmvc 中
*/
@PostConstruct
public void setReturnValueHandlers() {
List<HandlerMethodReturnValueHandler> returnValueHandlers = requestMappingHandlerAdapter
.getReturnValueHandlers();
/**
* 追加 Excel返回值处理器 到 springmvc 中
*/
@PostConstruct
public void setReturnValueHandlers() {
List<HandlerMethodReturnValueHandler> returnValueHandlers = requestMappingHandlerAdapter
.getReturnValueHandlers();

List<HandlerMethodReturnValueHandler> newHandlers = new ArrayList<>();
newHandlers.add(responseExcelReturnValueHandler);
assert returnValueHandlers != null;
newHandlers.addAll(returnValueHandlers);
requestMappingHandlerAdapter.setReturnValueHandlers(newHandlers);
}
List<HandlerMethodReturnValueHandler> newHandlers = new ArrayList<>();
newHandlers.add(responseExcelReturnValueHandler);
assert returnValueHandlers != null;
newHandlers.addAll(returnValueHandlers);
requestMappingHandlerAdapter.setReturnValueHandlers(newHandlers);
}

/**
* 追加 Excel 请求处理器 到 springmvc 中
*/
@PostConstruct
public void setRequestExcelArgumentResolver() {
List<HandlerMethodArgumentResolver> argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers();
List<HandlerMethodArgumentResolver> resolverList = new ArrayList<>();
resolverList.add(new RequestExcelArgumentResolver());
resolverList.addAll(argumentResolvers);
requestMappingHandlerAdapter.setArgumentResolvers(resolverList);
}
/**
* 追加 Excel 请求处理器 到 springmvc 中
*/
@PostConstruct
public void setRequestExcelArgumentResolver() {
List<HandlerMethodArgumentResolver> argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers();
List<HandlerMethodArgumentResolver> resolverList = new ArrayList<>();
resolverList.add(new RequestExcelArgumentResolver());
resolverList.addAll(argumentResolvers);
requestMappingHandlerAdapter.setArgumentResolvers(resolverList);
}

@Bean
@ConditionalOnMissingBean
public DictDataProvider dictDataProvider() {
return new DefaultDictDataProvider();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.pig4cloud.plugin.excel.annotation;

import com.pig4cloud.plugin.excel.vo.DictEnum;

import java.lang.annotation.*;

/**
* Excel dict type 属性
*
* @author lengleng
* @date 2024/08/30
*/
@Documented
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface DictTypeProperty {

/**
* 字典类型字段
* @return {@link String }
*/
String value() default "";

/**
* [有限]直接从系统字典枚举解析,不走缓存
* @return 与当前字典有关的系统字典枚举列表
*/
Class<? extends DictEnum>[] enums() default {};

}
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer m
.registerConverter(LocalTimeStringConverter.INSTANCE)
.registerConverter(LongStringConverter.INSTANCE)
.registerConverter(StringArrayConverter.INSTANCE)
.registerConverter(DictTypeConvert.INSTANCE)
.ignoreEmptyRow(requestExcel.ignoreEmptyRow())
.sheet()
.headRowNumber(requestExcel.headRowNumber())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package com.pig4cloud.plugin.excel.converters;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.pig4cloud.plugin.excel.annotation.DictTypeProperty;
import com.pig4cloud.plugin.excel.handler.DictDataProvider;
import com.pig4cloud.plugin.excel.kit.SpringContextKit;
import com.pig4cloud.plugin.excel.vo.DictEnum;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Objects;

/**
* dict 转换器
*
* @author lengleng
* @date 2024/08/30
*/
@Slf4j
public enum DictTypeConvert implements Converter<String> {

/**
* 实例
*/
INSTANCE;

/**
* 支持 Java Type Key
*
* @return {@link Class }
*/
@Override
public Class supportJavaTypeKey() {
return String.class;
}

/**
* 支持 Excel 键入键
*
* @return {@link CellDataTypeEnum }
*/
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}

/**
* 转换为 Java 数据
*
* @param cellData 单元格数据
* @param contentProperty content 属性
* @param globalConfiguration 全局配置
* @return {@link String }
* @throws Exception 异常
*/
@Override
public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws Exception {
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
return cellData.getStringValue();
}
Field field = contentProperty.getField();

DictTypeProperty declaredAnnotation = field.getDeclaredAnnotation(DictTypeProperty.class);
if (Objects.isNull(declaredAnnotation)) {
return cellData.getStringValue();
}

if (declaredAnnotation.enums().length != 0) {

DictEnum[] enums = declaredAnnotation.enums()[0].getEnumConstants();
return DictEnum.getValueByLabel(enums, cellData.getStringValue());
}

DictDataProvider dictDataProvider = SpringContextKit.getBean(DictDataProvider.class);
DictEnum[] dictEnums = dictDataProvider.getDict(declaredAnnotation.value());
if (dictEnums == null) {
return cellData.getStringValue();
}
return DictEnum.getValueByLabel(dictEnums, cellData.getStringValue());
}

/**
* 转换为 Excel 数据
*
* @param value 价值
* @param contentProperty content 属性
* @param globalConfiguration 全局配置
* @return {@link WriteCellData }<{@link String }>
*/
@Override
public WriteCellData<String> convertToExcelData(String value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws Exception {
Field field = contentProperty.getField();

DictTypeProperty declaredAnnotation = field.getDeclaredAnnotation(DictTypeProperty.class);
if (Objects.isNull(declaredAnnotation)) {
return new WriteCellData<>(value);
}

if (declaredAnnotation.enums().length != 0) {
DictEnum[] enums = declaredAnnotation.enums()[0].getEnumConstants();
return new WriteCellData<>(DictEnum.getLabelByValue(enums, value));
}

DictDataProvider dictDataProvider = SpringContextKit.getBean(DictDataProvider.class);
DictEnum[] dictEnums = dictDataProvider.getDict(declaredAnnotation.value());

if (dictEnums == null) {
return new WriteCellData<>(value);
}

String labelByValue = DictEnum.getLabelByValue(dictEnums, value);
if (labelByValue != null) {
return new WriteCellData<>(labelByValue);
}
return new WriteCellData<>(value);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ public ExcelWriter getExcelWriter(HttpServletResponse response, ResponseExcel re
.registerConverter(LocalTimeStringConverter.INSTANCE)
.registerConverter(LongStringConverter.INSTANCE)
.registerConverter(StringArrayConverter.INSTANCE)
.registerConverter(DictTypeConvert.INSTANCE)
.autoCloseStream(true)
.excelType(responseExcel.suffix())
.inMemory(responseExcel.inMemory());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.pig4cloud.plugin.excel.handler;

/**
* @author lengleng
* @date 2024/8/30
*/
public class DefaultDictDataProvider implements DictDataProvider {

}
Loading

0 comments on commit 259fc4a

Please sign in to comment.