本文主要是介绍EasyExcel导入去除所有空格,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
EasyExcel导入去除所有空格
EasyExcel导入有自带的autoTrim参数可以自动去除空格, 但不支持中文空格, 略显尴尬
故在issue3021找到了方案
然后稍作调整
自定义一个ConverterAdapter
package xxx.convert;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.property.ExcelContentProperty;
import lombok.AllArgsConstructor;/*** @author ly-chn*/
@AllArgsConstructor
public class TrimStringCellDataAdapter<T> implements Converter<T> , TrimCellString{Converter<T> converter;@Overridepublic Class<?> supportJavaTypeKey() {return converter.supportJavaTypeKey();}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {return converter.supportExcelTypeKey();}@Overridepublic T convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {return converter.convertToJavaData(trim(cellData), contentProperty, globalConfiguration);}
}
然后批量替换(这里是spring环境, 如果是其他环境自行在某个地方调用一下就行了, 只要是导入之前就行)
package xxx.runner;import cn.iocoder.yudao.framework.excel.core.convert.TrimStringCellDataAdapter;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKeyBuild;
import com.alibaba.excel.converters.DefaultConverterLoader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import java.util.Map;/*** 加载excel自定义Convert* @author ly-chn*/
@Slf4j
@Component
public class ExcelTrimConvertLoadRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args) throws Exception {Map<ConverterKeyBuild.ConverterKey, Converter<?>> readConverts = DefaultConverterLoader.loadAllConverter();// 遍历并修改convertsfor (Map.Entry<ConverterKeyBuild.ConverterKey, Converter<?>> entry : readConverts.entrySet()) {ConverterKeyBuild.ConverterKey key = entry.getKey();Converter<?> converter = entry.getValue();if (key.getClazz() == String.class) {entry.setValue(new TrimStringCellDataAdapter<>(converter));}}}
}
package xxx.convert;import com.alibaba.excel.metadata.data.ReadCellData;
import com.sdjiashi.common.util.StrUtils;/*** 用于去除cell中的空格** @author ly-chn*/
public interface TrimCellString {default <T> ReadCellData<T> trim(ReadCellData<T> cellData) {if (cellData == null || cellData.getStringValue() == null) {return cellData;}String stringValue = cellData.getStringValue();cellData.setStringValue(StrUtils.removeNbsp(stringValue));return cellData;}
}
这篇关于EasyExcel导入去除所有空格的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!