使用 csvhelper 将使用 Nodatime LocalDateTime 的对象保存为 csv

问题描述 投票:0回答:1

我正在尝试使用 csvhelper 库将对象列表保存到 csv 中。 对象看起来像这样:

public class AccountDTO {
    public string? Name { get; set; }
    public LocalDateTime CreatedDate { get; set; }
}

LocalDateTime 字段是一个 NodaTime.LocalDateTime。 我使用这种方法保存列表:

public void SaveAsCSV<T>(List<T> records, string path) {
    using var writer = new StreamWriter(path);
    using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
    csv.WriteRecords(records);
}

出于某种原因,它在 LocalDateTime 字段中保存包含所有元数据列的行,而不是仅保存字符串版本。

所以而不是显示为:

| Name     | CreatedDate|
| -------- | -----———-- |
| Name 1   | 2008-10-31T17:04:32|
| Name 2   | 2008-10-32T17:04:32|

它被保存为: csv view 或列:csv columns

我不太熟悉 csvhelper 和 nodatime 所以任何帮助将不胜感激。

我已经尝试了几个 csvhelper 类型的转换器解决方案,例如

public class LocalDateTimeConverter : ValueConverter<LocalDateTime, DateTime>
{
    public LocalDateTimeConverter() : base(
        localDateTime => localDateTime.ToDateTimeUnspecified(),
        dateTime => LocalDateTime.FromDateTime(dateTime))
    { }
}

和其他人,但到目前为止没有任何效果。

c# .net csvhelper nodatime
1个回答
1
投票

LocalDateTime
是一个类对象,
CsvHelper
正在写出该对象的所有属性。您可以在
Convert
中使用
ClassMap
来仅输出
ToString()
对象的
LocalDateTime
值。

void Main()
{
    var records = new List<AccountDTO>() {
        new AccountDTO {
            Name = "Name 1",
            CreatedDate = new LocalDateTime(2008,10,30,17,4,32)
        },
        new AccountDTO {
            Name = "Name 2",
            CreatedDate = new LocalDateTime(2008,10,31,17,4,32)
        }
    };

    using var csv = new CsvWriter(Console.Out, CultureInfo.InvariantCulture);

    csv.Context.RegisterClassMap<AccountDTOMap>();
    csv.WriteRecords(records);
}

public class AccountDTOMap : ClassMap<AccountDTO>
{
    public AccountDTOMap() 
    {
        Map(x => x.Name);
        Map(x => x.CreatedDate).Convert(args => args.Value.CreatedDate.ToString());
    }
}

public class AccountDTO
{
    public string? Name { get; set; }
    public LocalDateTime CreatedDate { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.