0

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

这是它正在生产的:

在此处输入图像描述

这是我所拥有的:

头文件.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);
    }

}
4

2 回答 2

2

这个怎么样:

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);
}
于 2019-03-15T16:36:28.553 回答
1

好的,想通了。我将地图更改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);
    }
于 2019-03-15T16:36:36.230 回答