CsvHelper : 将 List<string> 写入 CSV

CsvHelper : Writing List<string> to CSV

我想知道如何使用 CsvHelper 将列表写入 CSV。我看过了 here.

我在 CSV 文件中有以下属性 Class

public class CSV
{
    public int? Id { get; set; }
    public List<string> Header1 { get; set; }
    public string Header2 { get; set; }
    public string Header3 { get; set; }
    public string Header4 { get; set; }
    public long? Header5 { get; set; }
    public long? Header6 { get; set; }
    public long? Header7 { get; set; }
    public string Header8 { get; set; }
    public List<string> Header9 { get; set; }
    public List<string> Header10 { get; set; }
    public List<string> Header11 { get; set; }
}

写入 CSV

var records = new List<CSV>
{
    new CSV { Header1 = new List<string>{ "value1", "value2" } }
};

using (var writer = new StreamWriter("path\to\file.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(records);
}

最终结果应该是这样的

Header1
value1,value2

如有任何帮助,我们将不胜感激。

我猜您正在寻找这样的东西。这将从 Header1 列表中创建一个逗号分隔的字符串。

public class Program
{
    static void Main(string[] args)
    {        
        var records = new List<CSV>
        {
            new CSV { Id = 1, Header1 = new List<string>{ "value1", "value2" } }
        };

        using (var csv = new CsvWriter(Console.Out, CultureInfo.InvariantCulture))
        {
            csv.Configuration.RegisterClassMap<CSVMap>();
            csv.WriteRecords(records);
        }

        Console.ReadKey();
    }
}

public class CSVMap : ClassMap<CSV>
{
    public CSVMap()
    {
        AutoMap(CultureInfo.InvariantCulture);
        Map(m => m.Header1).ConvertUsing(row => string.Join(",", row.Header1)).Index(0);
    }
}

public class CSV
{
    public int? Id { get; set; }
    public List<string> Header1 { get; set; }
}

给你一个输出

Id,Header1
1,"value1,value2"