Java使用OpenCSV将List<GetProductModel>转为List<String[]>写入CSV
将产品对象列表转换为OpenCSV兼容格式的实现方案
核心逻辑就是遍历原始的产品对象列表,把每个对象的三个属性按固定顺序提取为字符串数组,收集后传给OpenCSV的写入方法即可,不需要额外引入其他依赖。
具体实现步骤
- 初始化目标
List<String[]>后,先添加CSV表头行,避免导出的文件没有列名无法识别字段含义 - 遍历已填充数据的
listProduct,对每个GetProductModel实例,通过对应的getter方法取出ProductName、Description、Price三个属性值,组装为和表头顺序一致的字符串数组 - 把所有组装好的行数组加入目标列表,直接传入原有CSV写入逻辑即可完成导出
核心转换代码参考:
// 初始化转换后的字符串数组列表 List<String[]> csvRows = new ArrayList<>(); // 写入表头,列名可以根据业务需要自行修改 csvRows.add(new String[]{"ProductName", "Description", "Price"}); // 遍历原始产品列表逐行转换 for (GetProductModel product : listProduct) { String[] row = new String[3]; // 按表头顺序填充字段值,做判空处理避免导出的CSV里出现"null"字样 row[0] = product.getProductName() != null ? product.getProductName() : ""; row[1] = product.getDescription() != null ? product.getDescription() : ""; row[2] = product.getPrice() != null ? product.getPrice() : ""; csvRows.add(row); } // 原有OpenCSV写入逻辑,直接传入转换完成的csvRows即可 try (CSVWriter writer = new CSVWriter(new FileWriter("c:\\test\\monitor.csv"))) { writer.writeAll(csvRows); } catch (Exception e) { e.printStackTrace(); }
小提示:如果使用Java 8及以上版本,也可以用Stream流简化遍历逻辑,本质和循环写法完全一致:
List<String[]> csvRows = new ArrayList<>(); csvRows.add(new String[]{"ProductName", "Description", "Price"}); listProduct.stream() .map(product -> new String[]{ product.getProductName() != null ? product.getProductName() : "", product.getDescription() != null ? product.getDescription() : "", product.getPrice() != null ? product.getPrice() : "" }) .forEach(csvRows::add);
内容的提问来源于stack exchange,提问作者Sekti Andarbeni
相关产品推荐
相关产品推荐

