using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Threading.Tasks; namespace IOB_UT_NEXT { public class DataExport { /// /// Effettua salvataggio in file di un generico oggetto in formato CSV /// /// /// Lista oggetti da esportare /// Percorso file di output /// Indica se scrivere header ad inizio CSV /// Separatore da impiegare (default ";") /// public static bool SaveToCsv(List reportData, string path, bool writeHeader, char separator = ';') { bool answ = false; var lines = new List(); try { IEnumerable props = TypeDescriptor.GetProperties(typeof(T)).OfType(); var elencoValori = props.ToList(); var header = string.Join($"{separator}", props.ToList().Select(x => !string.IsNullOrEmpty(x.Description) ? x.Description : x.Name)); var fieldList = string.Join($"{separator}", props.ToList().Select(x => x.Name)); if (writeHeader) { lines.Add(header); } var valueLines = reportData.Select(row => string.Join($"{separator}", fieldList.Split(separator).Select(a => row.GetType().GetProperty(a).GetValue(row, null)))); lines.AddRange(valueLines); File.WriteAllLines(path, lines.ToArray()); answ = true; } catch { } return answ; } /// /// Effettua salvataggio in file di un generico oggetto in formato Fixed width /// /// /// Lista oggetti da esportare /// Percorso file di output /// Vettore delle larghezze richieste /// public static bool SaveFixedWidth(List reportData, string path, Dictionary widthList, Dictionary fieldLPad, Dictionary numDecReq) { bool answ = false; var lines = new List(); try { IEnumerable props = TypeDescriptor.GetProperties(typeof(T)).OfType(); var elencoValori = props.ToList(); foreach (var dataRow in reportData) { string currRow = ""; // processo 1:1 x width... foreach (var item in widthList) { string currValue = dataRow.GetType().GetProperty(item.Key).GetValue(dataRow, null).ToString(); // se ha un num decimali specifico richiesto esegue... if (numDecReq.ContainsKey(item.Key)) { string nDec = $"N{numDecReq[item.Key]}"; decimal rawVal = 0; decimal.TryParse(currValue, out rawVal); currValue = rawVal.ToString(nDec); } if (currValue.Length > item.Value) { currValue = currValue.Substring(0, item.Value); } // se ha un LPad richiesto esegue... if (fieldLPad.ContainsKey(item.Key)) { currValue = currValue.PadLeft(item.Value, fieldLPad[item.Key]); } currRow += string.Format($"{{0,-{item.Value}}}", currValue); } lines.Add(currRow); } File.WriteAllLines(path, lines.ToArray()); answ = true; } catch { } return answ; } } }