package com.skyversation.poiaddr.util; import java.io.FileWriter; import java.io.IOException; import java.util.*; public class CsvWriter { /** * 将 List> 类型的数据写入 CSV 文件 * @param data 要写入的数据 * @param filePath CSV 文件的保存路径 * @throws IOException 如果写入文件时发生 I/O 错误 */ public static void writeToCsv(List> data, String filePath) throws IOException { if (data == null || data.isEmpty()) { return; } // 获取所有的列名 Set headers = new LinkedHashSet<>(); for (Map row : data) { headers.addAll(row.keySet()); } // 将列名写入 CSV 文件 try (FileWriter writer = new FileWriter(filePath)) { writeLine(writer, new ArrayList<>(headers)); // 遍历数据,将每一行写入 CSV 文件 for (Map row : data) { List values = new ArrayList<>(); for (String header : headers) { Object value = row.get(header); values.add(value != null ? value.toString() : ""); } writeLine(writer, values); } } } /** * 将一行数据写入 CSV 文件 * @param writer 文件写入器 * @param values 一行数据的值 * @throws IOException 如果写入文件时发生 I/O 错误 */ private static void writeLine(FileWriter writer, List values) throws IOException { boolean firstValue = true; for (String value : values) { if (!firstValue) { writer.append(","); } writer.append(escapeCsv(value)); firstValue = false; } writer.append("\n"); } /** * 转义 CSV 中的特殊字符 * @param value 要转义的值 * @return 转义后的字符串 */ private static String escapeCsv(String value) { if (value == null) { return ""; } boolean needsQuotes = value.contains(",") || value.contains("\"") || value.contains("\n"); if (needsQuotes) { value = value.replace("\"", "\"\""); return "\"" + value + "\""; } return value; } public static void main(String[] args) { List> data = new ArrayList<>(); Map item = new HashMap<>(); item.put("列名1","test00"); item.put("列名3","test02"); Map item2 = new HashMap<>(); item2.put("列名2","test11"); item2.put("列名3","test12"); data.add(item); data.add(item2); // 这里可以添加测试数据 try { writeToCsv(data, "C:\\Users\\Liumouren\\Desktop\\outputTest.csv"); System.out.println("CSV 文件写入成功!"); } catch (IOException e) { System.err.println("写入 CSV 文件时发生错误:" + e.getMessage()); } } }