原 easyexcel(七):数据类型转换
版权声明:本文为博主原创文章,请尊重他人的劳动成果,转载请附上原文出处链接和本声明。
本文链接:https://www.91mszl.com/zhangwuji/article/details/1262
我们在读取excel的时候,有时候会遇到数据转换的问题。如单元格里面显示的是(872),其实它是-872.27
数据类型转换有2种方法,
@ExcelProperty(index = 10, converter = StringNumberConverter.class)
private String month1; // 一月[销量]
StringNumberConverter 转换类
package com.mszl.utils;
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;
// 自定义格式转换
public class StringNumberConverter implements Converter<String> {
@Override
public Class supportJavaTypeKey() {
return String.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
/**
* 这里读的时候会调用
*/
@Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
String result=null;
CellDataTypeEnum dataType=cellData.getType();
if(dataType==CellDataTypeEnum.NUMBER){
result=cellData.getNumberValue().toString();
} else{
result=cellData.getStringValue();
}
return result;
}
/**
* 这里是写的时候会调用 不用管
*/
@Override
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return new CellData(value);
}
}
方法二:对整个读取的excel的字段进行统一转换(全局转换)。
EasyExcel.read(iv.getFileUrl(), dataListener).headRowNumber(3).registerConverter(new FloatStringConverter()).sheet().doRead();
FloatStringConverter转换类代码如下:
package com.mszl.utils;
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 org.apache.poi.ss.formula.functions.T;
import java.math.BigDecimal;
// 自定义格式转换
public class FloatStringConverter implements Converter<String> {
@Override
public Class supportJavaTypeKey() {
return String.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.NUMBER;
}
@Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
String result=null;
CellDataTypeEnum dataType=cellData.getType();
if(dataType==CellDataTypeEnum.NUMBER){
result=cellData.getNumberValue().toString();
} else{
result=cellData.getStringValue();
}
return result;
}
@Override
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return null;
}
}
2020-08-23 16:29:10 阅读(8308)
名师出品,必属精品 https://www.91mszl.com
博主信息