当前位置:网站首页>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);
}
边栏推荐
- "Digital economy, science and technology for the good" talk about dry goods
- Li Hang, director of ByteDance AI Lab: past, present and future of language model
- 小程序毕设作品之微信校园洗衣小程序毕业设计成品(5)任务书
- Keras deep learning practice - recommend system data coding
- Huiliang technology app is a good place to go to sea: after more than ten years of popularity, why should the United States still choose to go to sea for gold
- We should learn to check the documented instructions of technical details
- Accuracy improvement method: efficient visual transformer framework of adaptive tokens (open source)
- The salary level of programmers in various countries is a little miserable
- 13. User web layer services (I)
- 【每日一题】1206. 设计跳表
猜你喜欢

The universe has no end. Can utonmos shine the meta universe into reality?

Product manager experience 100 (XI) - Strategic Product Manager: model and methodology

利用C语言实现URL解析的基本方法之优秀

剑指Offer 07 重建二叉树 -- 从中序与后序遍历序列构造二叉树

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

小程序毕设作品之微信校园洗衣小程序毕业设计成品(5)任务书

Wechat campus laundry applet graduation design finished product (7) Interim inspection report

egg-swagger-doc 图形验证码解决方案

Echart line chart displays the last point and vertical dotted line by default
![[C Advanced] pointer array vs array pointer](/img/1e/33f9cc9446dcad8cdb78babbb5a22c.jpg)
[C Advanced] pointer array vs array pointer
随机推荐
Vertical and horizontal shooting range - the mystery of the picture
[introduction to C language] zzulioj 1021-1025
Crop the large size image of target detection into a fixed size image
在“元宇宙空间”UTONMOS将打开虚实结合的数字世界
基于C语言实现线性表的建立、插入、删除、查找等基本操作
The universe has no end. Can utonmos shine the meta universe into reality?
Onnxruntime [reasoning framework, which users can easily use to run an onnx model]
Futures Commission Standard and margin ratio
Gray histogram
【2022-07-25】
SQL教程之 SQL 聚合函数入门教程
leetcode——83,24; Machine learning - neural networks
UTNet 用于医学图像分割的混合Transformer
小程序毕设作品之微信校园洗衣小程序毕业设计成品(2)小程序功能
See if you are on the shortlist of each division
js回调函数(callback)
MySQL high availability practical solution MHA
【LeetCode】592. 分数加减运算
看看有没有你,各赛区入围名单
Product manager experience 100 (XI) - Strategic Product Manager: model and methodology