繁体   English   中英

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

[英]Write CSV from List of HashMaps with Header using Apache Commons CSV

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

这是它产生的:

在此处输入图片说明

这是我所拥有的:

头文件

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);
    }

}

这个怎么样:

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);
}

确定了。 我将地图更改为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);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM