EasyExcel(二) 导入导出excel的数据格式转换

EasyExcel(二) 导入导出excel的数据格式转换

一、准备工作

这是我用的版本

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.2.6</version>
</dependency>

二、讲解Converter< T>

  1. 讲解
public interface Converter<T> {
          
   
    // 在java中的类型是什么
    Class supportJavaTypeKey();
    // 在excel中的类型是什么
    CellDataTypeEnum supportExcelTypeKey();
	// 将excel的数据类型转为java数据类型
    T convertToJavaData(CellData var1, ExcelContentProperty var2, GlobalConfiguration var3) throws Exception;
	// 将java的数据类型转为excel数据类型
    CellData convertToExcelData(T var1, ExcelContentProperty var2, GlobalConfiguration var3) throws Exception;
}
  1. 示例
public class GenderConverter implements Converter<String> {
          
   
    //在java中性别是用 0 1 来标识的  所以是int
    @Override
    public Class supportJavaTypeKey() {
          
   return Integer.class;}
	// 在excel中是男女 所以是string
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
          
   return CellDataTypeEnum.STRING;}
	//将excel的数据类型转为java数据类型
    @Override
    public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
          
   
        String stringValue = cellData.getStringValue();
        if (stringValue == null) {
          
   
            throw new RuntimeException("性别填写为空");
        }
        if ("男".equals(stringValue)) {
          
   
           return 1;
        }
         return 0;
    }
	//将java的数据类型转为excel数据类型
    @Override
    public CellData convertToExcelData(Integer s, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
          
   
        if	(s == 0){
          
   
             return new CellData("女");
        }
        return new CellData("男");
    }
}
当然 其中也有一些默认的数据转换器
// 这里用string 去接日期才能格式化。我想接收年月日格式
@DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")
// 我想接收百分比的数字
@NumberFormat("#.##%")

--------------最后感谢大家的阅读,愿大家技术越来越流弊!--------------

--------------也希望大家给我点支持,谢谢各位大佬了!!!--------------

经验分享 程序员 微信小程序 职场和发展