CsvHelper,编写动态变量名(c#)

CsvHelper, writing dynamic variable names (c#)

假设要以以下 csv 文件格式写入银行用户帐户详细信息。

AccountId, Name, Jan, Feb, Mar ........... Dec
1, Anne, 1000.00, 400.00, 500.00 .......... 200.00
2, John, 900.00, 400.00, 500.00 .......... 1200.00
3, Brit, 600.00, 400.00, 500.00 .......... 2200.00

为了表示上述数据结构,我有以下模型class:

class AccountBalance {
      int ID { get; set; };
      string Name { get; set; };
      List<string> lastTwelveMonths { get; set; };
}

我的代码是写csv是:

using (var stream = new MemoryStream())
using (var streamWriter = new StreamWriter(stream))
using (var stringWriter = new StringWriter())
using (var csvWriter = new CsvWriter(stringWriter))
{
    csvWriter.WriteRecords(listOfAccountBalances);
    streamWriter.Write(stringWriter.GetStringBuilder());
    streamWriter.Flush();
    stream.Position = 0;
    return stream.ToArray();
}

但是当涉及到 lastTwelveMonths 的列表时,上面的代码不会给出准确的输出。有人可以帮忙吗?

您应该可以使用自定义 class地图来做到这一点:

sealed class AccountBalanceMap : ClassMap<AccountBalance>
{
    public AccountBalanceMap()
    {
        Map(x => x.ID);
        Map(x => x.Name);
        Map(x => x.lastTwelveMonths, false)
            .Name("Jan")
            .ConvertUsing(row => $"{row.lastTwelveMonths[0]}");
        Map(x => x.lastTwelveMonths, false)
            .Name("Feb")
            .ConvertUsing(row => $"{row.lastTwelveMonths[1]}");
        // ...
    }

使用 CsvWriter 之前注册 class 地图:

csv.Configuration.RegisterClassMap<AccountBalanceMap>();

您甚至可以使用 DateTimeFormatInfo.CurrentInfo.GetMonthName

动态构建 class 地图
sealed class AccountBalanceMap : ClassMap<AccountBalance>
{
    public AccountBalanceMap()
    {
        Map(x => x.ID);
        Map(x => x.Name);
        for (int i = 0; i < 12; i++)
        {
            var monthName = DateTimeFormatInfo.CurrentInfo.GetMonthName(i + 1);
            var monthIndex = i;
            Map(x => x.lastTwelveMonths, false)
                .Name(monthName)
                .ConvertUsing((row) => $"{row.lastTwelveMonths[monthIndex]}");
        }
    }
}