You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.7 KiB

1 year ago
  1. package com.inscloudtech.common.convert;
  2. import cn.hutool.core.annotation.AnnotationUtil;
  3. import cn.hutool.core.convert.Convert;
  4. import cn.hutool.core.util.ObjectUtil;
  5. import com.alibaba.excel.converters.Converter;
  6. import com.alibaba.excel.enums.CellDataTypeEnum;
  7. import com.alibaba.excel.metadata.GlobalConfiguration;
  8. import com.alibaba.excel.metadata.data.ReadCellData;
  9. import com.alibaba.excel.metadata.data.WriteCellData;
  10. import com.alibaba.excel.metadata.property.ExcelContentProperty;
  11. import com.inscloudtech.common.annotation.ExcelDictFormat;
  12. import com.inscloudtech.common.core.service.DictService;
  13. import com.inscloudtech.common.utils.StringUtils;
  14. import com.inscloudtech.common.utils.poi.ExcelUtil;
  15. import com.inscloudtech.common.utils.spring.SpringUtils;
  16. import lombok.extern.slf4j.Slf4j;
  17. import java.lang.reflect.Field;
  18. /**
  19. * 字典格式化转换处理
  20. *
  21. * @author inscloudtech
  22. */
  23. @Slf4j
  24. public class ExcelDictConvert implements Converter<Object> {
  25. @Override
  26. public Class<Object> supportJavaTypeKey() {
  27. return Object.class;
  28. }
  29. @Override
  30. public CellDataTypeEnum supportExcelTypeKey() {
  31. return null;
  32. }
  33. @Override
  34. public Object convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
  35. ExcelDictFormat anno = getAnnotation(contentProperty.getField());
  36. String type = anno.dictType();
  37. String label = cellData.getStringValue();
  38. String value;
  39. if (StringUtils.isBlank(type)) {
  40. value = ExcelUtil.reverseByExp(label, anno.readConverterExp(), anno.separator());
  41. } else {
  42. value = SpringUtils.getBean(DictService.class).getDictValue(type, label, anno.separator());
  43. }
  44. return Convert.convert(contentProperty.getField().getType(), value);
  45. }
  46. @Override
  47. public WriteCellData<String> convertToExcelData(Object object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
  48. if (ObjectUtil.isNull(object)) {
  49. return new WriteCellData<>("");
  50. }
  51. ExcelDictFormat anno = getAnnotation(contentProperty.getField());
  52. String type = anno.dictType();
  53. String value = Convert.toStr(object);
  54. String label;
  55. if (StringUtils.isBlank(type)) {
  56. label = ExcelUtil.convertByExp(value, anno.readConverterExp(), anno.separator());
  57. } else {
  58. label = SpringUtils.getBean(DictService.class).getDictLabel(type, value, anno.separator());
  59. }
  60. return new WriteCellData<>(label);
  61. }
  62. private ExcelDictFormat getAnnotation(Field field) {
  63. return AnnotationUtil.getAnnotation(field, ExcelDictFormat.class);
  64. }
  65. }