Я хотел бы установить формат для всех дат в файле CSV, созданном CSVHelper CSVWriter. В приложении .NET Core (.NET 7.0, C# V11, CSVHELPER V30.0.1) я смог поместить < /p>
Код: Выделить всё
// Add default format for nullable and non-nullable dates
var csvContext = new CsvContext(new CsvConfiguration(CultureInfo.InvariantCulture));
csvContext.TypeConverterOptionsCache.GetOptions().Formats = new[] { "yyyy-MM-dd" };
csvContext.TypeConverterOptionsCache.GetOptions().Formats = new[] { "yyyy-MM-dd" };
Код: Выделить всё
public static void Main()
{
var fileBytes = Array.Empty();
var data = new List {
new Foo{Id=987654, Name="Smith, John", Birthdate=DateTime.Parse("3/22/1972"),EntryDate=DateTime.Parse("8/26/2024") },
new Foo{Id=654321, Name="Doe, Jane", Birthdate=DateTime.Parse("8/29/1963"),EntryDate=DateTime.Parse("8/26/2024") }
};
var csvConfiguration = new CsvConfiguration(CultureInfo.CurrentCulture);
using (var memoryStream = new MemoryStream())
{
using (var streamWriter = new StreamWriter(memoryStream))
{
using (var csvWriter = new CsvWriter(streamWriter, csvConfiguration))
{
csvWriter.Context.RegisterClassMap(new FooMap());
csvWriter.WriteRecords(data);
}
}
fileBytes = memoryStream.ToArray();
}
HttpContext current = HttpContext.Current;
current.Trace.IsEnabled = false;
current.Response.Clear();
current.Response.ContentType = "application/octet-stream"; // or application/force-download
current.Response.AddHeader("content-disposition", "attachment; filename=SelectedRecords.csv");
current.Response.BinaryWrite(fileBytes);
current.Response.End();
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime? Birthdate { get; set; }
public DateTime? WithdrawDate { get; set; }
public DateTime? EntryDate { get; set; }
}
public class FooMap : ClassMap
{
public FooMap()
{
var csvContext = new CsvContext(new CsvConfiguration(CultureInfo.InvariantCulture));
// Works: the undesired format is successfully applied
// Comment these two lines out and uncomment the following lines.
// The output is '3/22/1972' - the original value with no addt'l formatting
csvContext.TypeConverterOptionsCache.GetOptions().Formats = new[] { "yyyy#MM-dd" };
csvContext.TypeConverterOptionsCache.GetOptions().Formats = new[] { "yyyy#MM-dd" };
//csvContext.TypeConverterOptionsCache.GetOptions().Formats = new[] { "yyyy-MM-dd" };
//csvContext.TypeConverterOptionsCache.GetOptions().Formats = new[] { "yyyy-MM-dd" };
AutoMap(csvContext);
}
}
Подробнее здесь: https://stackoverflow.com/questions/794 ... formatting
Мобильная версия