使用CSV助手将字符串的嵌套列表写入CSV

6psbrbz9  于 2023-06-03  发布在  其他
关注(0)|答案(1)|浏览(127)

我有一个嵌套的字符串列表,我想写一个CSV文件使用CSV助手。因此,它是一个名为Entries的列表,每个元素都有一个名为Entry的字符串列表。
我当前的代码是导出一个空白的CSV文件。
Entry示例:

{"Date", "param1", "param2", "param3", "param4"}

并且Entries列表将具有那些的列表。
我想写一个CSV文件,每个条目都是一个新的行。
预期结局:

"Date", "param1", "param2", "param3", "param4"
"Date", "param1", "param2", "param3", "param4"
"Date", "param1", "param2", "param3", "param4"
"Date", "param1", "param2", "param3", "param4"

当前代码:

var rawDataList = await _siteRepository.GetRawSiteData(siteGuid);

var Entries = _siteRepository.GetSiteData(rawDataList);
var writer = new StreamWriter("YodelTesting.csv");
var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);

foreach(var record in Entries)
{
    csv.WriteRecord(record);
}

帮助将不胜感激!

e4eetjau

e4eetjau1#

我用了现在的代码让它工作

using (var stream = new MemoryStream())
using (var writer = new StreamWriter("yodelTesting.csv"))
using (var reader = new StreamReader(stream))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    foreach (var record in output)
    {
        foreach (var field in record)
        {
            csv.WriteField(field);

        }
        csv.NextRecord();
    }
    //not sure what this does tbh
    writer.Flush();
    stream.Position = 0;
}

相关问题