解决使用 easyexcel 导出 excel 文件时报错 Can not find ‘Converter‘ support class List.
解决使用 easyexcel 导出 excel 文件时报错 Can not find 'Converter' support class List.
文章共1,256字 · 阅读需要大约5分钟
一键AI生成摘要,助你高效阅读
问答
·
1.问题描述
在项目中,我想使用 easyexcel 将数据库中的数据导出到 excel 文件中,要导出的实体类属性如下,可以看到有一个属性为List <String>
类型。
执行写出程序后报错结果如下:
com.alibaba.excel.exception.ExcelDataConvertException: Can not find 'Converter' support class List.
2.报错原因
EasyExcel
开源框架中 Converter 接口的 convertToExcelData 只实现了转换BigDecimal、Bolean、Byte[]、btye[]、Byte、Date、Double、File、Float、InputStream、Integer、Long、Short、URL这些类型,意味着参数 data 最多只能是个二维数据,但是本次业务逻辑需要转换 List< String > 的数据。
3.解决办法
编写自定义Converter转换器:
@Component
public class ListConverter implements Converter<List> {
@Override
public Class supportJavaTypeKey() {
return List.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public List convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
String stringValue = cellData.getStringValue();
String[] split = stringValue.split(";");
List<String> tags = new ArrayList<>();
for(int i = 0; i < split.length; i++){
tags.add(split[i]);
}
return tags;
}
@Override
public CellData convertToExcelData(List list, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
StringBuilder stringBuilder = new StringBuilder();
list.forEach(o -> {
String s = o.toString();
stringBuilder.append(s+";");
});
return new CellData(stringBuilder.toString());
}
}
然后在要转换的属性上注解或者在写出时指定转换器,两种方式都可以:
第一种方式
@ExcelProperty(value = "资源标签",converter = ListConverter.class)
private List<String> tags;
第二种方式
@Autowired
private ListConverter listConverter;
public void exportData(HttpServletResponse response) {
// .....
EasyExcel.write(response.getOutputStream(), ExcelEntity.class)
.registerConverter(listConverter)
.sheet("资源列表")
.doWrite(ExcelEntityList);
// .....
}
参考文章:https://blog.csdn.net/qq_41049371/article/details/120156305
更多推荐
已为社区贡献1条内容
所有评论(0)