44 lines
1.6 KiB
C#
44 lines
1.6 KiB
C#
using System.Globalization;
|
|
using CsvHelper;
|
|
using CsvHelper.Configuration;
|
|
using CsvHelper.TypeConversion;
|
|
|
|
namespace FKGees.Services;
|
|
|
|
internal class CsvService
|
|
{
|
|
private ILogger<App> _logger;
|
|
|
|
public CsvService(ILogger<App> logger)
|
|
{
|
|
_logger = logger;
|
|
}
|
|
|
|
internal async Task CsvExport<T>(string filePath, IEnumerable<T> records)
|
|
{
|
|
try
|
|
{
|
|
await using var writer = new StreamWriter(filePath);
|
|
IWriterConfiguration conf = new CsvConfiguration(CultureInfo.InvariantCulture)
|
|
{
|
|
Delimiter = ";",
|
|
Mode = CsvMode.RFC4180,
|
|
ShouldQuote = quoteArgs => quoteArgs.Field != nameof(DecretsResult.Data)
|
|
&& quoteArgs.Field != nameof(DecretsResult.DataWplywu)
|
|
&& !DateTime.TryParseExact(quoteArgs.Field, Constants.DefaultDateFormat, CultureInfo.InvariantCulture,
|
|
DateTimeStyles.None, out _)
|
|
};
|
|
await using var csv = new CsvWriter(writer, conf);
|
|
var options = new TypeConverterOptions { Formats = [Constants.DefaultDateFormat], NullValues = { string.Empty }};
|
|
csv.Context.TypeConverterOptionsCache.AddOptions<DateTime>(options);
|
|
csv.Context.TypeConverterOptionsCache.AddOptions<DateTime?>(options);
|
|
|
|
await csv.WriteRecordsAsync(records);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
_logger.LogError(e, "Error");
|
|
throw;
|
|
}
|
|
}
|
|
} |