gpt4 book ai didi

c# - 使用 CsvHelper 生成带有动态 header 的 CSV

转载 作者:行者123 更新时间:2023-12-05 05:01:45 26 4
gpt4 key购买 nike

我的数据库中有一条记录,我想生成 CSV,为此我正在使用 CsvHelper 库。下面给出了需要生成为 csv 的记录的数据结构。 enter image description here观察者“additional_details”列,它包含一个 JSON 对象。应在 csv 输出中为每个唯一的 JSON 键添加一个新列。见下图 enter image description here

这就是我目前正在尝试做的:-

 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();
}

最佳答案

这是 AddRecordAsync 的更新版本。您还需要将 _addintionalDetails 传递给它。

private static async Task AddRecordAsync(CsvWriter csvWriter, Data row, Dictionary<string, string> _addintionalDetails)
{
csvWriter.WriteRecord(row);

var additional = row.AdditionalDetails as IDictionary<string, object>;

foreach (var header in _addintionalDetails)
{
if (additional.ContainsKey(header.Key))
{
csvWriter.WriteField(additional[header.Key]);
}
else
{
csvWriter.WriteField(string.Empty);
}
}

await csvWriter.NextRecordAsync();
}

关于c# - 使用 CsvHelper 生成带有动态 header 的 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62618814/

26 4 0
文章推荐: azure-devops - Azure 管道中部署作业中的条件批准门
文章推荐: node.js - 仅当 mongodb 中的 operationType 为 'update' 时才过滤
文章推荐: python - PyAudio:如何以回调/非阻塞模式访问 stream.read() 数据
文章推荐: python-3.x - UnexpectedTagNameException : Message: Select only works on