比如需求需要csv的导出格式如下:“张三”|李四“|“王五”|“赵六”
看能不能新增自定义格式的功能
anauzrmj1#
import com.alibaba.excel.EasyExcel; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.write.builder.ExcelWriterBuilder; import com.alibaba.excel.write.metadata.WriteSheet; import java.util.ArrayList; import java.util.List; public class CustomCSVFormatExample { public static void main(String[] args) { String fileName = "output.csv"; // 准备数据 List<CustomData> dataList = new ArrayList<>(); dataList.add(new CustomData("张三", "李四", "王五", "赵六")); // 写入 CSV 文件 EasyExcel.write(fileName, CustomData.class) .sheet("Sheet1") .registerConverter(new CustomCSVConverter()) // 注册自定义的 Converter .doWrite(dataList); } // POJO 类 public static class CustomData { @ExcelProperty(index = 0) private String name1; @ExcelProperty(index = 1) private String name2; @ExcelProperty(index = 2) private String name3; @ExcelProperty(index = 3) private String name4; // 构造函数、getter 和 setter 方法 public CustomData(String name1, String name2, String name3, String name4) { this.name1 = name1; this.name2 = name2; this.name3 = name3; this.name4 = name4; } } // 自定义的 Converter 实现 public static class CustomCSVConverter implements Converter<String> { @Override public Class supportJavaTypeKey() { return String.class; } @Override public String convertToExcelData(String value, com.alibaba.excel.metadata.CellData cellData, com.alibaba.excel.metadata.Head head, com.alibaba.excel.write.metadata.WriteSheet writeSheet) { return "\"" + value + "\""; // 将字段值用双引号包裹 } @Override public String convertToJavaData(String value, com.alibaba.excel.metadata.CellData cellData, com.alibaba.excel.metadata.Head head, com.alibaba.excel.read.metadata.ReadSheet readSheet) { return value; // 不需要实现读取方法 } } }
k10s72fa2#
现在 4.0.1 版本通过自定义 Conveter 这种方式好像会输出 """
2条答案
按热度按时间anauzrmj1#
k10s72fa2#
现在 4.0.1 版本通过自定义 Conveter 这种方式好像会输出 """