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

时间:2018-08-10 05:25:18

标签: c# csvhelper

假设要以以下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 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列表时,以上代码将无法给出确切的输出。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您应该可以使用自定义的类映射来做到这一点:

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之前注册类映射:

csv.Configuration.RegisterClassMap<AccountBalanceMap>();

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

动态地构建类映射
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]}");
        }
    }
}