简体   繁体   English

使用 HashMap 中的列和值创建 CSV 文件

[英]Create CSV file with columns and values from HashMap

Be gentle, This is my first time using Apache Commons CSV 1.7.温和一点,这是我第一次使用 Apache Commons CSV 1.7。

I am creating a service to process some CSV inputs, add some additional information from exterior sources, then write out this CSV for ingestion into another system.我正在创建一个服务来处理一些 CSV 输入,从外部来源添加一些额外的信息,然后写出这个 CSV 以引入另一个系统。

I store the information that I have gathered into a list of HashMap<String, String> for each row of the final output csv.我将收集到的信息存储到最终输出 csv 的每一行的HashMap<String, String>列表中。 The Hashmap contains the <ColumnName, Value for column> . Hashmap 包含<ColumnName, Value for column>

I have issues using the CSVPrinter to correctly assign the values of the HashMaps into the rows.我在使用 CSVPrinter 将 HashMap 的值正确分配到行中时遇到问题。 I can concatenate the values into a string with commas between the variables;我可以将值连接成一个字符串,变量之间用逗号分隔; however, this just inserts the whole string into the first column.然而,这只是将整个字符串插入第一列。

I cannot define or hardcode the headers since they are obtained from a config file and may change depending on which project uses the service.我无法定义或硬编码标头,因为它们是从配置文件中获取的,并且可能会根据使用该服务的项目而改变。

Here is some of my code:这是我的一些代码:

try (BufferedWriter writer = Files.newBufferedWriter(
    Paths.get(OUTPUT + "/" + project + "/" + project + ".csv"));)
{
    CSVPrinter csvPrinter = new CSVPrinter(writer,
        CSVFormat.RFC4180.withFirstRecordAsHeader());
    csvPrinter.printRecord(columnList);

for (HashMap<String, String> row : rowCollection)
{
    //Need to map __record__ to column -> row.key, value -> row.value for whole map.

    csvPrinter.printrecord(__record__);
}

csvPrinter.flush();

}

Thanks for your assistance.谢谢你的协助。

You actually have multiple concerns with your technique;您实际上对自己的技术有多种担忧;

  1. How do you maintain column order?您如何维护列顺序?
  2. How do you print the column names?你如何打印列名?
  3. How do you print the column values?你如何打印列值?

Here are my suggestions.这是我的建议。

  1. Maintain column order.保持列顺序。 Do not use HashMap , because it is unordered.不要使用HashMap ,因为它是无序的。 Instead, use LinkedHashMap which has a "predictable iteration order" (ie maintains order).相反,使用具有“可预测的迭代顺序”(即维护顺序)的LinkedHashMap

  2. Print column names.打印列名称。 Every row in your list contains the column names in the form of key values, but you only print the column names as the first row of output.列表中的每一行都包含键值形式的列名,但您只将列名打印为输出的第一行。 The solution is to print the column names before you loop through the rows.解决方案是在遍历行之前打印列名。 Get them from the first element of the list.从列表的第一个元素中获取它们。

  3. Print column values.打印列值。 The "billal GHILAS" answer demonstrates a way to print the values of each row. “billal GHILAS”答案演示了一种打印每行值的方法。

Here is some code:这是一些代码:

try (BufferedWriter writer = Files.newBufferedWriter(
     Paths.get(OUTPUT + "/" + project + "/" + project + ".csv"));)
{
    CSVPrinter csvPrinter = new CSVPrinter(writer,
        CSVFormat.RFC4180.withFirstRecordAsHeader());

    // This assumes that the rowCollection will never be empty.
    // An anonymous scope block just to limit the scope of the variable names.
    {
        HashMap<String, String> firstRow = rowCollection.get(0);
        int valueIndex = 0;
        String[] valueArray = new String[firstRow.size()];

        for (String currentValue : firstRow.values())
        {
            valueArray[valueIndex++] = currentValue;
        }

        csvPrinter.printrecord(valueArray);
    }

    for (HashMap<String, String> row : rowCollection)
    {
        int valueIndex = 0;
        String[] valueArray = new String[row.size()];

        for (String currentValue : row.values())
        {
            valueArray[valueIndex++] = currentValue;
        }

        csvPrinter.printrecord(valueArray);
    }

    csvPrinter.flush();
}
for (HashMap<String,String> row : rowCollection) {
       Object[] record = new Object[row.size()];
       for (int i = 0; i < columnList.size(); i++) {
            record[i] = row.get(columnList.get(i));
       }

       csvPrinter.printRecord(record);
 }

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

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