Ho trovato questo codice e l’ho riadattato all’esigenza che avevo di esportare una List<T> dove T può essere un qualsiasi oggetto in un file CSV.
public static class ExportListToCSV
{
/// <summary>
/// Ottengo da una List<T> una stringa csv
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static string GetCsv<T>(List<T> list)
{
var separator = ";";
var sb = new StringBuilder();
//Ricerco le intestazioni delle colonne "dati"
var propInfos = typeof(T).GetProperties();
for (var i = 0; i <= propInfos.Length - 1; i++)
{
sb.Append(propInfos[i].Name);
if (i < propInfos.Length - 1)
{
sb.Append(separator);
}
}
sb.AppendLine();
//Ciclo tutti i dati inserendo le righe nello string builder
for (int i = 0; i <= list.Count - 1; i++)
{
T item = list[i];
for (int j = 0; j <= propInfos.Length - 1; j++)
{
object o = item.GetType().GetProperty(propInfos[j].Name).GetValue(item, null);
if (o != null)
{
string value = o.ToString();
if (value.Contains(separator))
{
value = string.Concat(""", value, """);
}
//Rimuovo gli eventuali "a capo" e altri caratteri speciali
if (value.Contains("r"))
{
value = value.Replace("r", " ");
}
if (value.Contains("n"))
{
value = value.Replace("n", " ");
}
sb.Append(value);
}
if (j < propInfos.Length - 1)
{
sb.Append(separator);
}
}
sb.AppendLine();
}
return sb.ToString();
}
/// <summary>
/// Esporta la List<T> nel file indicato
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">Lista da concertire</param>
/// <param name="filename">File di destinazione</param>
public static void ExportCSV<T>(List<T> list, string filename)
{
string csv = GetCsv(list);
var sw = new StreamWriter(filename);
sw.Write(csv);
sw.Close();
}
}
About Diego Mancinelli
Da sempre appassionato di informatica e tutto ciò che riaguarda l' Information Tecnology. Mi occupo di progettazione, analisi e sviluppo di software e applicazioni web per piattaforme Windows, Android, iOS