我在我的数据库中有一些记录,我想生成CSV文件,我正在使用CsvHelper库来实现。需要生成CSV的记录的数据结构如下所示。
观察"additional_details"列,它包含一个JSON对象。应该为每个唯一的JSON键在csv输出中添加一个新列。请参见下面的图片。
![enter image description here](https://istack.dev59.com/gCRre.webp)
![enter image description here](https://istack.dev59.com/HWRGk.webp)
这是我目前正在尝试做的事情:
My c# model
public class Data
{
public bool ConfirmedAttendance {get; set;}
public bool DigitalDelivery {get; set;}
public string ProfileCode {get; set;}
public ExpandoObject AdditionalDetails { get; set; }
}
So, I will be getting a `IList<Data> _data;`
using var stream = new MemoryStream();
using var writer = new StreamWriter(stream);
using var csvWriter = new CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture);
csvWriter.Configuration.HasHeaderRecord = true;
csvWriter.WriteHeader<Data>();
//A dictionary to hold each column and its value.
var _addintionalDetails = new Dictionary<string, string>();
//populating the above dictionary with the unique json key.
foreach (var record in _data)
{
foreach (var item in (IDictionary<String, Object>)record.AdditionalDetails)
{
if(!_addintionalDetails.ContainsKey(item.Key))
{
_addintionalDetails.Add(item.Key, item.Value.ToString());
}
}
}
//Adding new column in the csv output from the above dictionary.
foreach (var header in _addintionalDetails)
{
csvWriter.WriteField(header.Key.Humanize(LetterCasing.AllCaps));
}
await csvWriter.NextRecordAsync();
//Adding records to my csv
foreach (var row in input.Records)
{
//How to add records for additional details ??
await AddRecordAsync(csvWriter, row);
}
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
input.Stream = stream.ToArray();
private static async Task AddRecordAsync(CsvWriter csvWriter, Data row)
{
csvWriter.WriteRecord<Data>(row);
await csvWriter.NextRecordAsync();
}