[英]Write List of Maps to a CSV
我有一個獨立的應用程序,該應用程序連接到SQL數據庫並將ResultSet保存在Map列表中。 這是我到目前為止的內容:
List<Map<String, Object>> rows;
stmt = conn.createStatement();
Resultset rs = stmt.executeQuery(queryString);
ResultSetMetaData rsmd; //Properties of Resultset object and column count
while(rs.next){
Map<String, Object> rowResult = new HashMap<String, Object>(columnCount);
for(int i =1; i <=columnCount; i++){
rowResult.put(rsmd.getColumnName(i), rs.getObject(i));
}
rows.add(rowResult);
}
//WRITE TO CSV
String csv = "C:\\Temp\\data.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
//Write the record to file
writer.writeNext(rows);
//close the writer
writer.close();
如何將列表的“行”添加到帶有列的csv中? 任何線索和建議。 感謝您的幫助。
由於每條記錄將以相同的順序具有相同的列,因此我只對行使用List<List<Object>>
。
對於標題,您不需要在每一行上都獲取它們。 只需一次獲得它們,如下所示:
List<String> headers = new ArrayList<>();
for (int i = 1; i <= columnCount; i++ )
{
String colName = rsmd.getColumnName(i);
headers.add(colName);
}
接下來,您可以獲取以下行:
List<List<Object>> rows = new ArrayList<>();
while(rs != null && rs.next)
{
List<Object> row = new ArrayList<>();
for(int i =1; i <=columnCount; i++)
{
row.add(rs.getObject(i));
}
rows.add(row);
}
最后,要創建CSV文件,您可以執行以下操作:
// create the CSVWriter
String csv = "C:\\Temp\\data.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
// write the header line
for (String colName : headers)
{
writer.write(colName);
}
writer.endRecord();
// write the data records
for (List<Object> row : rows)
{
for (Object o : row)
{
// handle nulls how you wish here
String val = (o == null) ? "null" : o.toString();
writer.write(val);
}
writer.endRecord();
}
// you should close the CSVWriter in a finally block or use a
// try-with-resources Statement
writer.close;
注意 :在我的代碼示例中,我正在使用類型推斷
請參閱 : Try-With-Resources語句 。
老實說,我建議您在CSVWriter中使用writeAll方法並傳遞ResultSet 。
writer.writeAll(rs, true);
第二個參數是include列名,因此csv文件中的第一行將是列名。 然后,當您讀取文件時,可以根據需要將其轉換回Map中(盡管它將是所有字符串,除非您在讀取文件時知道類型是什么)。
希望能有所幫助。
斯科特:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.