使用Apache Commons CSV工具将List<Map<String,Object>>写入csv并保存

需求如题
源数据类型:List<Map<String,String>>或者List<Map<String,Object>>
List<Map<String,String>>类型的数据
想将这样的数据写入csv并保存到某个位置
方法:
借助Apache Commons CSV工具来转换

1、引入依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.9.0</version>
</dependency>

2、list2csv函数
其中涉及到Apache Commons CSV的操作参考了https://www.baeldung.com/apache-commons-csv

/**
* @Description: convert list<Map<>> to csv
* @Param: list<Map<>>,pathName
* @return:
*/
public void list2csv(List<Map<String,String>> list,String pathName) throws IOException {
    List<String> headerList = new ArrayList<>();
    for (String s : list.get(0).keySet()) {
        headerList.add(s);
    }
    String[] csvHeader = headerList.toArray(new String[headerList.size()]);

    FileWriter out = new FileWriter(pathName); //要写入的位置 如D:/test.csv
    try (CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT
            .withHeader(csvHeader))) {
        for(Map<String,String> map:list) {
            List<String> valueList = new ArrayList<>();
            for(String s:headerList)
                valueList.add(map.get(s));
            String[] csvValue = valueList.toArray(new String[valueList.size()]);
            printer.printRecord(csvValue);
        }
    }
}

有更好的方法欢迎交流~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值