当前位置:网站首页>Converter registration of easyexcel
Converter registration of easyexcel
2022-07-27 13:55:00 【lang20150928】
In the use of easyexcel Error in template export
Caused by: com.alibaba.excel.exception.ExcelWriteDataConvertException: Can not find 'Converter' support class Timestamp.
at com.alibaba.excel.write.executor.AbstractExcelWriteExecutor.doConvert(AbstractExcelWriteExecutor.java:323)
at com.alibaba.excel.write.executor.AbstractExcelWriteExecutor.convert(AbstractExcelWriteExecutor.java:277)
at com.alibaba.excel.write.executor.ExcelWriteFillExecutor.doFill(ExcelWriteFillExecutor.java:258)
at com.alibaba.excel.write.executor.ExcelWriteFillExecutor.fill(ExcelWriteFillExecutor.java:127)
at com.alibaba.excel.write.ExcelBuilderImpl.fill(ExcelBuilderImpl.java:82)
at com.alibaba.excel.ExcelWriter.fill(ExcelWriter.java:107)
at com.alibaba.excel.ExcelWriter.fill(ExcelWriter.java:95)
at com.xQuant.platform.common.excel.utils.ExportData2ExcelUtil.lambda$export2Excel$0(ExportData2ExcelUtil.java:95)
at java.util.HashMap.forEach(HashMap.java:1289)
at com.xQuant.platform.common.excel.utils.ExportData2ExcelUtil.export2Excel(ExportData2ExcelUtil.java:88)
at com.xQuant.platform.common.excel.utils.ExportData2ExcelUtil.export2Excel(ExportData2ExcelUtil.java:115)
at com.S3003.cams.query.bo.CommonQueryBO.genExcel(CommonQueryBO.java:406)
... 79 common frames omitted
It can be seen from the error message that , There is no converter .
Create the following converter by referring to the official source code
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.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.WorkBookUtil;
import org.apache.poi.ss.usermodel.DateUtil;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;
public class EasyTimestampConverter implements Converter<Timestamp> {
@Override
public Class<?> supportJavaTypeKey() {
return Timestamp.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public Timestamp convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException {
Date javaDate;
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
javaDate = DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(),
globalConfiguration.getUse1904windowing(), null);
} else {
javaDate = DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(),
contentProperty.getDateTimeFormatProperty().getUse1904windowing(), null);
}
if (javaDate != null){
return new Timestamp(javaDate.getTime());
}else {
return null;
}
}
@Override
public WriteCellData<?> convertToExcelData(Timestamp value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws Exception {
WriteCellData<?> cellData = new WriteCellData<>(value);
String format = null;
if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) {
format = contentProperty.getDateTimeFormatProperty().getFormat();
}
WorkBookUtil.fillDataFormat(cellData, format, DateUtils.defaultDateFormat);
return cellData;
}
}
And then execute excel Register during operation
try (ExcelWriter excelWriter = EasyExcel.write(outputFile.getPath()).withTemplate(excelTemplateFile).registerConverter(new EasyTimestampConverter()).build()) {
// ... excel Operation logic
}
According to the truth , It should be OK at this time . however , Error is still reported when the program is executed .
Only source code analysis …
Check the error source code com.alibaba.excel.write.executor.AbstractExcelWriteExecutor#doConvert
private WriteCellData<?> doConvert(CellWriteHandlerContext cellWriteHandlerContext) {
ExcelContentProperty excelContentProperty = cellWriteHandlerContext.getExcelContentProperty();
Converter<?> converter = null;
if (excelContentProperty != null) {
converter = excelContentProperty.getConverter();
}
if (converter == null) {
// csv is converted to string by default
if (writeContext.writeWorkbookHolder().getExcelType() == ExcelTypeEnum.CSV) {
cellWriteHandlerContext.setTargetCellDataType(CellDataTypeEnum.STRING);
}
converter = writeContext.currentWriteHolder().converterMap().get(
ConverterKeyBuild.buildKey(cellWriteHandlerContext.getOriginalFieldClass(),
cellWriteHandlerContext.getTargetCellDataType()));
}
if (cellWriteHandlerContext.getOriginalValue() == null && !(converter instanceof NullableObjectConverter)) {
return new WriteCellData<>(CellDataTypeEnum.EMPTY);
}
if (converter == null) {
throw new ExcelWriteDataConvertException(cellWriteHandlerContext,
"Can not find 'Converter' support class " + cellWriteHandlerContext.getOriginalFieldClass()
.getSimpleName() + ".");
}
WriteCellData<?> cellData;
try {
cellData = ((Converter<Object>)converter).convertToExcelData(
new WriteConverterContext<>(cellWriteHandlerContext.getOriginalValue(), excelContentProperty,
writeContext));
} catch (Exception e) {
throw new ExcelWriteDataConvertException(cellWriteHandlerContext,
"Convert data:" + cellWriteHandlerContext.getOriginalValue() + " error, at row:"
+ cellWriteHandlerContext.getRowIndex(), e);
}
if (cellData == null || cellData.getType() == null) {
throw new ExcelWriteDataConvertException(cellWriteHandlerContext,
"Convert data:" + cellWriteHandlerContext.getOriginalValue()
+ " return is null or return type is null, at row:"
+ cellWriteHandlerContext.getRowIndex());
}
return cellData;
}
One of the most critical behaviors
converter = writeContext.currentWriteHolder().converterMap().get(
ConverterKeyBuild.buildKey(cellWriteHandlerContext.getOriginalFieldClass(),
cellWriteHandlerContext.getTargetCellDataType()));
stay debug When ,converterMap() It includes its own defined converter , But the corresponding key incorrect . When is the converter defined by yourself stored in convertMap What about the middle ? Continue to view source code , Last in com.alibaba.excel.write.metadata.holder.AbstractWriteHolder#AbstractWriteHolder The corresponding logic is found .
if (writeBasicParameter.getCustomConverterList() != null
&& !writeBasicParameter.getCustomConverterList().isEmpty()) {
for (Converter<?> converter : writeBasicParameter.getCustomConverterList()) {
getConverterMap().put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey()), converter);
}
}

You can see that the mapping is built when finding the converter and storing the converter key Values in different ways .( Calculate or calculate bug Well ??)
And then we studied DefaultConverterLoader 了 , Discovery can be achieved by loadDefaultWriteConverter Method to get the corresponding Map
public static Map<ConverterKey, Converter<?>> loadDefaultWriteConverter() {
return defaultWriteConverter;
}
Can be obtained Map Then add the converter by yourself ( In the use of EasyExcel Add the following code to the class of )
static {
EasyTimestampConverter converter = new EasyTimestampConverter();
DefaultConverterLoader.loadDefaultWriteConverter().put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey(), converter.supportExcelTypeKey()), converter);
}
边栏推荐
- 现在还来得及参加9月份的PMP考试吗?
- Recommended collection, confusing knowledge points of PMP challenge (2)
- Structural thinking
- Tencent cloud and the China Federation of industry released the research results of industrial AI quality inspection standardization to accelerate the intelligent transformation of manufacturing indus
- 期货手续费标准和保证金比例
- opencv图像的缩放平移及旋转
- What are the benefits of taking NPDP
- OPPO 自研大规模知识图谱及其在数智工程中的应用
- Gains and losses of desensitization project
- There is no need for semantic segmentation of annotation data! Eth & Leuven University proposed maskdistill, using transformer for unsupervised semantic segmentation, SOTA
猜你喜欢

Keras deep learning practice - recommend system data coding

《C语言》函数栈帧的创建与销毁--(内功)

JS 模块、闭包应用

使用RecyclerView,实现列表左滑菜单

基于C语言实现线性表的建立、插入、删除、查找等基本操作

【C进阶】指针数组 VS 数组指针

For.. of can be used to traverse which data

Sword finger offer II 041. Average value of sliding window
idea Gradle7.0+ :Could not find method compile()

基于STM32的自由度云台运动姿态控制系统
随机推荐
Wechat campus laundry applet graduation design finished product of applet completion work (8) graduation design thesis template
Dat.gui control custom placement and dragging
16 VMware horizon 2203 virtual desktop-win10 automatic desktop pool full clone dedicated (XVI)
Cesium region clipping, local rendering
深度置信网络(DBN)【经典的DBN网络结构是由若干层 RBM(受限波尔兹曼机)和一层 BP 组成的一种深层神经网络】
Product manager experience 100 (XI) - Strategic Product Manager: model and methodology
【图论】负环
Vertical and horizontal shooting range - the mystery of the picture
Network packet loss, network delay? This artifact helps you get everything done!
Redis cluster setup - use docker to quickly build a test redis cluster
2022ACM夏季集训周报(四)
Leetcode error reporting and its solution
Creation and destruction of "C language" function stack frame -- (internal skill)
In the "meta cosmic space", utonmos will open the digital world of the combination of virtual and real
[daily question] 1206. Design jump table
Fiddler抓包工具+夜神模拟器
English grammar_ Personal pronoun
Swiftui map encyclopedia use mapkit to search
Software system architecture designer concise tutorial | software system modeling
使用RecyclerView,实现列表左滑菜单