需求如题
源数据类型:List<Map<String,String>>或者List<Map<String,Object>>
想将这样的数据写入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);
}
}
}
有更好的方法欢迎交流~