Esportare una List in un file CSV in C#

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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

Ultimo Aggiornamento il .

Lascia un commento