使用Apache Commons CSV从带有标题的HashMap列表中写入CSV

时间:2019-03-15 16:13:54

标签: java apache-commons apache-commons-csv

我必须使用ArrayList中的HashMap并使用Apache Commons CSV创建CSV。但是,它没有将值写入正确的标题。有没有一种简单的方法可以使库使用Enum自动将值放置在正确的标题中?我不想手动分配它,因为我将添加更多列。

这就是它产生的东西:

enter image description here

这是我所拥有的:

Header.java

public enum Header
{
    FIRST_NAME(),
    LAST_NAME(),
    GENDER();
}

主要

public static void main(String[] args)
{
    List<Map<Header, String>> output = new ArrayList<>();

    Map<Header, String> map = new HashMap<>();
    map.put(Header.FIRST_NAME, "John");
    map.put(Header.LAST_NAME, "Andrew");
    map.put(Header.GENDER, "Male");
    output.add(map);

    Map<Header, String> map2 = new HashMap<>();
    map2.put(Header.FIRST_NAME, "Sally");
    map2.put(Header.LAST_NAME, "Andrew");
    map2.put(Header.GENDER, "Female");
    output.add(map2);

    String outputFile = System.getProperty("java.io.tmpdir")+"test.csv";

    try (
            BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile));
            CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
                    .withHeader(Header.class));)
    {
        csvPrinter.printRecords(output);
        csvPrinter.flush();
    } catch (IOException ex)
    {
        Logger.getLogger(TestCSV.class.getName()).log(Level.SEVERE, null, ex);
    }

}

2 个答案:

答案 0 :(得分:1)

如何?

try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile));
        CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(Header.class));) {
    for (Map<Header, String> row : output) {
        csvPrinter.printRecord(Arrays.asList(Header.values())
                                     .stream()
                                     .map(header -> row.get(header))
                                     .collect(Collectors.toList()));
    }
} catch (IOException ex) {
    Logger.getLogger(TestCSV.class.getName())
          .log(Level.SEVERE, null, ex);
}

答案 1 :(得分:0)

好了。我将地图更改为LinkedHashMap以保留顺序,然后执行了此操作:

   try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile));
        CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
        .withHeader(Header.class));)
   {

        for (Map<Header, String> val : output)
        {
            csvPrinter.printRecord(val.values().toArray());
        }

        csvPrinter.flush();

    } catch (IOException ex)
    {
        Logger.getLogger(TestCSV.class.getName()).log(Level.SEVERE, null, ex);
    }