| | | 1 | | using ArturRios.Data.Export.Abstractions; |
| | | 2 | | using ArturRios.Data.Export.Configuration; |
| | | 3 | | |
| | | 4 | | namespace ArturRios.Data.Export.Exporters; |
| | | 5 | | |
| | | 6 | | /// <summary>Writes records as RFC 4180 CSV using the shared column map.</summary> |
| | | 7 | | /// <typeparam name="T">The record type.</typeparam> |
| | | 8 | | /// <param name="options">CSV options.</param> |
| | 8 | 9 | | public class CsvExporter<T>(CsvOptions options) : ExporterBase<T> where T : class |
| | | 10 | | { |
| | | 11 | | /// <inheritdoc /> |
| | | 12 | | protected override async Task WriteCoreAsync(IEnumerable<T> data, Stream destination, CancellationToken ct) |
| | 6 | 13 | | { |
| | 6 | 14 | | var columns = ColumnMap.For<T>(); |
| | 6 | 15 | | await using var writer = new StreamWriter(destination, options.Encoding, leaveOpen: true); |
| | | 16 | | |
| | 6 | 17 | | if (options.IncludeHeader) |
| | 5 | 18 | | { |
| | 5 | 19 | | await writer.WriteLineAsync(string.Join(options.Delimiter, |
| | 20 | 20 | | columns.Select(c => Escape(c.Header, options.Delimiter)))); |
| | 5 | 21 | | } |
| | | 22 | | |
| | 28 | 23 | | foreach (var item in data) |
| | 5 | 24 | | { |
| | 5 | 25 | | ct.ThrowIfCancellationRequested(); |
| | 5 | 26 | | await writer.WriteLineAsync(string.Join(options.Delimiter, |
| | 20 | 27 | | columns.Select(c => Escape(ValueRenderer.Render(c.Getter(item)), options.Delimiter)))); |
| | 5 | 28 | | } |
| | | 29 | | |
| | 6 | 30 | | await writer.FlushAsync(ct); |
| | 6 | 31 | | } |
| | | 32 | | |
| | | 33 | | private static string Escape(string field, char delimiter) |
| | 30 | 34 | | { |
| | 30 | 35 | | var mustQuote = field.Contains(delimiter) || field.Contains('"') || field.Contains('\n') || field.Contains('\r') |
| | 30 | 36 | | return mustQuote ? $"\"{field.Replace("\"", "\"\"")}\"" : field; |
| | 30 | 37 | | } |
| | | 38 | | } |