实现 easyExcel 导入导出自定义字典转换器

一、easyExcel 字典转换器 Converter

easyExcel 导入导出自定义字典转换器,包括导入字典转换以及导出字典转换。适配多个逗号分隔的字典值转换。

1、excel 导入字典转换注解

import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

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

/**
 * excel导入字典转换注解
 * <p>
 * 将excel导入的字典label自动转换为字典code
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JacksonAnnotationsInside
@JsonSerialize(using = DictItemSerialize.class)
public @interface ExcelDictItemLabel {

	/**
	 * 字典type
	 */
	String type();

}

2、excel 导出字典转换注解

import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

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

/**
 * excel导出字典转换注解
 * <p>
 * 将excel导出的字典code自动转换为字典label
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JacksonAnnotationsInside
@JsonSerialize(using = DictItemSerialize.class)
public @interface ExcelDictItem {

	/**
	 * 字典type
	 */
	String type();

}

3、自定义 excel 转换器

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.whitemeen.magic.common.core.constant.CacheConstants;
import com.whitemeen.magic.common.core.constant.SecurityConstants;
import com.whitemeen.magic.common.core.util.R;
import com.whitemeen.magic.common.core.util.SpringContextHolder;
import com.whitemeen.magic.upms.modules.admin.api.entity.SysDictItem;
import com.whitemeen.magic.upms.modules.admin.api.feign.RemoteDictService;
import com.whitemeen.magic.upms.modules.admin.config.ExcelDictItem;
import com.whitemeen.magic.upms.modules.admin.config.ExcelDictItemLabel;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Excel Converter字典转换器
 */
public class ExcelDictConverter implements Converter<String> {

	public ExcelDictConverter() {
	}

	@Override
	public Class supportJavaTypeKey() {
		return null;
	}

	@Override
	public CellDataTypeEnum supportExcelTypeKey() {
		return null;
	}

	/**
	 * 将excel单元格数据转换成对象属性值(适配多个逗号分隔的字典值)
	 *
	 * @param cellData             单元格的数据
	 * @param excelContentProperty excel每一行的数据内容
	 * @param globalConfiguration  global全局配置
	 * @return 转换后的对象属性值
	 * @throws Exception 异常
	 */
	@Override
	public String convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
		// 获取字典类型
		Field field = excelContentProperty.getField();
		ExcelDictItemLabel excel = field.getAnnotation(ExcelDictItemLabel.class);
		String dictType = excel.type();

		// 为空返回
		String dictLabel = cellData.getStringValue();
		if (StrUtil.isBlank(dictLabel)) {
			return dictLabel;
		}

		// 查询字典
		CacheManager cacheManager = SpringContextHolder.getBean(CacheManager.class);
		Cache dictCache = cacheManager.getCache(CacheConstants.DICT_DETAILS);
		R<List<SysDictItem>> dictItemListR = dictCache.get(dictType, R.class);

		if (dictItemListR == null) {
			RemoteDictService dictService = SpringContextHolder.getBean(RemoteDictService.class);
			dictItemListR = dictService.customize(dictType, SecurityConstants.FROM_IN);
		}
		if (dictItemListR == null || CollectionUtils.isEmpty(dictItemListR.getData())) {
			return dictLabel;
		}

		// 将字典项根据label分组
		Map<String, SysDictItem> dictItemLabelMap = dictItemListR.getData()
				.stream().collect(Collectors.toMap(SysDictItem::getLabel, Function.identity(), (v1, v2) -> v2));

		// 存在多个字典项值
		List<String> dictLabelList = Arrays.stream(dictLabel.split(",")).collect(Collectors.toList());
		StringBuilder dictValues = new StringBuilder();

		// 字典转换拼接
		for (String sourcesDictLabel : dictLabelList) {
			SysDictItem sysDictItem = dictItemLabelMap.get(sourcesDictLabel);
			if (sysDictItem == null) {
				continue;
			}

			if (StrUtil.isBlank(dictValues)) {
				dictValues.append(sysDictItem.getItemValue());
			} else {
				dictValues.append(",").append(sysDictItem.getItemValue());
			}
		}

		return String.valueOf(dictValues);
	}

	
//	/**
//	 * 将excel单元格数据转换成对象属性值(仅适配单个字典值)
//	 *
//	 * @param cellData             单元格的数据
//	 * @param excelContentProperty excel每一行的数据内容
//	 * @param globalConfiguration  global全局配置
//	 * @return 转换后的对象属性值
//	 * @throws Exception 异常
//	 */
//	@Override
//	public String convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
//		// 获取字典类型
//		Field field = excelContentProperty.getField();
//		ExcelDictItemLabel excel = field.getAnnotation(ExcelDictItemLabel.class);
//		String dictType = excel.type();
//
//		String dictLabel = cellData.getStringValue();
//		if (StrUtil.isBlank(dictLabel)) {
//			return dictLabel;
//		}
//		// 查询字典
//		RemoteDictService remoteDictService = SpringContextHolder.getBean(RemoteDictService.class);
//		R<List<SysDictItem>> dictItemsR = remoteDictService.getDictByType(dictType);
//		if (CollectionUtil.isEmpty(dictItemsR.getData())) {
//			return dictLabel;
//		}
//		// 进行字典翻译
//		String javaData = dictLabel;
//		List<SysDictItem> dictItems = dictItemsR.getData();
//		for (SysDictItem dictItem : dictItems) {
//			if (StrUtil.equals(dictLabel, dictItem.getLabel())) {
//				javaData = dictItem.getItemValue();
//				break;
//			}
//		}
//		return javaData;
//	}

	/**
	 * 将对象属性值转换成excel单元格数据(适配多个逗号分隔的字典值)
	 *
	 * @param dictValue            对象的属性值
	 * @param excelContentProperty excel每一行的数据内容
	 * @param globalConfiguration  global全局配置
	 * @return 转换后的对象属性值
	 * @throws Exception 异常
	 */
	@Override
	public CellData convertToExcelData(String dictValue, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
		// 获取字典类型
		Field field = excelContentProperty.getField();
		ExcelDictItem excel = field.getAnnotation(ExcelDictItem.class);
		String dictType = excel.type();

		// 为空返回
		if (StrUtil.isBlank(dictValue)) {
			return new CellData(dictValue);
		}

		// 查询字典
		CacheManager cacheManager = SpringContextHolder.getBean(CacheManager.class);
		Cache dictCache = cacheManager.getCache(CacheConstants.DICT_DETAILS);
		R<List<SysDictItem>> dictItemListR = dictCache.get(dictType, R.class);

		if (dictItemListR == null) {
			RemoteDictService dictService = SpringContextHolder.getBean(RemoteDictService.class);
			dictItemListR = dictService.customize(dictType, SecurityConstants.FROM_IN);
		}
		if (dictItemListR == null || CollectionUtils.isEmpty(dictItemListR.getData())) {
			return new CellData(dictValue);
		}

		// 将字典项根据value分组
		Map<String, SysDictItem> dictItemValueMap = dictItemListR.getData()
				.stream().collect(Collectors.toMap(SysDictItem::getItemValue, Function.identity(), (v1, v2) -> v2));

		// 存在多个字典项值
		List<String> dictValueList = Arrays.stream(dictValue.split(",")).collect(Collectors.toList());
		StringBuilder dictLabels = new StringBuilder();

		// 字典转换拼接
		for (String sourcesDictLabel : dictValueList) {
			SysDictItem sysDictItem = dictItemValueMap.get(sourcesDictLabel);
			if (sysDictItem == null) {
				continue;
			}

			if (StrUtil.isBlank(dictLabels)) {
				dictLabels.append(sysDictItem.getLabel());
			} else {
				dictLabels.append(",").append(sysDictItem.getLabel());
			}
		}

		if(StrUtil.isBlank(String.valueOf(dictLabels))){
			return new CellData(dictValue);
		}
		return new CellData(String.valueOf(dictLabels));
	}
	
//	/**
//	 * 将对象属性值转换成excel单元格数据(仅适配单个字典值)
//	 *
//	 * @param dictValue            对象的属性值
//	 * @param excelContentProperty excel每一行的数据内容
//	 * @param globalConfiguration  global全局配置
//	 * @return 转换后的对象属性值
//	 * @throws Exception 异常
//	 */
//	@Override
//	public CellData convertToExcelData(String dictValue, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
//		// 获取字典类型
//		Field field = excelContentProperty.getField();
//		String fieldName = field.getName();
//		DictItem excel = field.getAnnotation(DictItem.class);
//		String dictType = excel.type();
//		// 查询字典
//		RemoteDictService remoteDictService = SpringContextHolder.getBean(RemoteDictService.class);
//		R<List<SysDictItem>> dictItemsR = remoteDictService.getDictByType(dictType);
//		if (CollectionUtil.isEmpty(dictItemsR.getData())) {
//			return new CellData(dictValue);
//		}
//		// 进行字典翻译
//		String excelData = dictValue;
//		List<SysDictItem> dictItems = dictItemsR.getData();
//		for (SysDictItem dictItem : dictItems) {
//			if (StrUtil.equals(dictValue, dictItem.getItemValue())) {
//				excelData = dictItem.getLabel();
//				break;
//			}
//		}
//		return new CellData(excelData);
//	}

}

4、使用 excel 字典转换注解


	/**
	 * 性别label(用于接收与展现真实的excel内容)
	 */
	@ExcelProperty(value = "性别", converter = ExcelDictConverter.class)
	@ExcelDictItemLabel(type = "gender")
	private String genderLabel;

	/**
	 * 性别code(用来承载java对象属性值)
	 */
	@ExcelIgnore
	@ExcelDictItem(type = "gender")
	private String gender;
	
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是使用 Java 实现 EasyExcel 导入导出的示例代码: 1. 引入 EasyExcel 依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.1.7</version> </dependency> ``` 2. 定义 Excel 数据模型: ```java public class User { @ExcelProperty("姓名") private String name; @ExcelProperty("年龄") private Integer age; // 省略 getter 和 setter 方法 } ``` 3. 编写 Excel 数据读取代码: ```java public void readExcel(File excelFile) { EasyExcel.read(excelFile, User.class, new AnalysisEventListener<User>() { @Override public void invoke(User user, AnalysisContext analysisContext) { // 处理读取到的数据 System.out.println(user); } @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { // 读取完毕后的操作 } }).sheet().doRead(); } ``` 4. 编写 Excel 数据写入代码: ```java public void writeExcel(File excelFile, List<User> userList) { EasyExcel.write(excelFile, User.class).sheet().doWrite(userList); } ``` 5. 配置 Excel 文件的格式: 可以使用注解或配置文件来设置 Excel 文件的格式,例如: ```java public class User { @ExcelProperty(value = "姓名", index = 0) private String name; @ExcelProperty(value = "年龄", index = 1) @ColumnWidth(15) private Integer age; // 省略 getter 和 setter 方法 } ``` 6. 执行导入导出操作: ```java File excelFile = new File("test.xlsx"); // 读取 Excel 文件 readExcel(excelFile); // 写入 Excel 文件 List<User> userList = new ArrayList<>(); userList.add(new User("张三", 20)); userList.add(new User("李四", 25)); writeExcel(excelFile, userList); ``` 总的来说,使用 EasyExcel 进行 Excel 文件的导入导出操作非常简单,只需要几行代码即可完成。同时,EasyExcel 还提供了丰富的 API,可以满足不同场景下的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Whitemeen太白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值