using System.Globalization; using System.IO; using System.Linq.Expressions; namespace zero.Utils; public class TableBuilder : ITableBuilder, IDisposable { protected List> Columns { get; set; } protected TableFormat Format { get; set; } protected CultureInfo Culture { get; set; } public TableBuilder(TableFormat format, CultureInfo culture = null) { Format = format; Columns = new List>(); Culture = culture ?? new CultureInfo("de-DE"); // TODO get culture from zero config Culture.NumberFormat.CurrencyDecimalSeparator = ","; Culture.NumberFormat.CurrencyGroupSeparator = " "; } /// public string GetExtension() { return Format switch { TableFormat.Csv => ".csv", TableFormat.Excel => ".xlsx", _ => throw new NotSupportedException($"The table format {Format} is not supported") }; } /// public MemoryStream ToStream(IEnumerable source) { ITableCreator creator = Format switch { TableFormat.Csv => new CsvCreator(Columns), TableFormat.Excel => new ExcelCreator(Columns), _ => throw new NotSupportedException($"The table format {Format} is not supported") }; return creator.CreateStream(source, Culture); } /// public async Task ToStream(IAsyncEnumerable source) { ITableCreator creator = Format switch { TableFormat.Csv => new CsvCreator(Columns), TableFormat.Excel => new ExcelCreator(Columns), _ => throw new NotSupportedException($"The table format {Format} is not supported") }; return await creator.CreateStream(source, Culture); } /// public TableColumn Column(string name, Expression> fieldSelector = null, double width = 15, TableColumnType type = TableColumnType.Default) { TableColumn column = new() { Name = name, FieldSelector = fieldSelector?.Compile(), Width = width, ColumnType = type }; Columns.Add(column); return column; } /// public void Scope(Action action) { action(default); } /// public TableColumn Separator() { TableColumn column = new() { IsSeparator = true, Width = 4 }; Columns.Add(column); return column; } /// public void Dispose() { //Stream?.Dispose(); //Workbook?.Dispose(); } } public interface ITableBuilder { /// /// Get file extension calculated by TableFormat /// string GetExtension(); /// /// Add a new column to the table /// TableColumn Column(string name, Expression> fieldSelector = null, double width = 12, TableColumnType type = TableColumnType.Default); /// /// /// void Scope(Action action); /// /// Adds an empty column which acts as a separator /// TableColumn Separator(); /// /// Creates a memory stream from the provided source /// MemoryStream ToStream(IEnumerable source); /// /// Creates a memory stream from the provided source /// Task ToStream(IAsyncEnumerable source); /// /// Disposes the underlying table creator /// void Dispose(); }