[英]Create CSV file with columns and values from HashMap
溫和一點,這是我第一次使用 Apache Commons CSV 1.7。
我正在創建一個服務來處理一些 CSV 輸入,從外部來源添加一些額外的信息,然后寫出這個 CSV 以引入另一個系統。
我將收集到的信息存儲到最終輸出 csv 的每一行的HashMap<String, String>
列表中。 Hashmap 包含<ColumnName, Value for column>
。
我在使用 CSVPrinter 將 HashMap 的值正確分配到行中時遇到問題。 我可以將值連接成一個字符串,變量之間用逗號分隔; 然而,這只是將整個字符串插入第一列。
我無法定義或硬編碼標頭,因為它們是從配置文件中獲取的,並且可能會根據使用該服務的項目而改變。
這是我的一些代碼:
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();
}
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.