44 lines
1.8 KiB
C#
44 lines
1.8 KiB
C#
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
|
|
{
|
|
|
|
/// <summary>
|
|
/// Effettua salvataggio in file di un generico oggetto in formato CSV
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <param name="reportData"></param>
|
|
/// <param name="path"></param>
|
|
/// <param name="separator">Separatore da impiegare (default ";")</param>
|
|
/// <returns></returns>
|
|
public static bool SaveToCsv<T>(List<T> reportData, string path, char separator = ';')
|
|
{
|
|
bool answ = false;
|
|
var lines = new List<string>();
|
|
try
|
|
{
|
|
IEnumerable<PropertyDescriptor> props = TypeDescriptor.GetProperties(typeof(T)).OfType<PropertyDescriptor>();
|
|
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));
|
|
lines.Add(header);
|
|
var valueLines = reportData.Select(row => string.Join($"{separator}", fieldList.Split(separator).Select(a => row.GetType().GetProperty(a).GetValue(row, null))));
|
|
//var valueLines = reportData.Select(row => string.Join(";", header.Split(';').Select(a => row.GetType().GetProperty(a).GetValue(row, null))));
|
|
lines.AddRange(valueLines);
|
|
File.WriteAllLines(path, lines.ToArray());
|
|
answ = true;
|
|
}
|
|
catch
|
|
{ }
|
|
return answ;
|
|
}
|
|
}
|
|
}
|