小心一点,这是我第一次使用Apache Commons CSV 1.7。
我正在创建一个服务来处理一些CSV输入,从外部来源添加一些其他信息,然后将该CSV写出以便提取到另一个系统中。
我将收集的信息存储到HashMap<String, String>
最终输出csv的每一行的列表中。Hashmap包含<ColumnName, Value for column>
。
我在使用CSVPrinter正确地将HashMaps的值分配到行中时遇到问题。我可以将值连接成一个字符串,变量之间用逗号隔开;但是,这只是将整个字符串插入第一列。
我无法定义或硬编码标题,因为它们是从配置文件中获取的,并且可能会根据使用服务的项目而有所变化。
这是我的一些代码:
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();
}
谢谢你的协助。
实际上,您对技术有多种关注;
这是我的建议。
保持列顺序。不要使用HashMap
,因为它是无序的。而是使用LinkedHashMap
具有“可预测的迭代顺序”(即保持顺序)的。
打印列名。列表中的每一行都包含键值形式的列名,但是您仅将列名打印为输出的第一行。解决方案是在循环浏览行之前打印列名称。从列表的第一个元素中获取它们。
打印列值。“ Billal GHILAS”答案演示了一种打印每行值的方法。
这是一些代码:
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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句