I am trying to use the following code to generate CSV file:
public static IEnumerable<string> ToCsv<T>(IEnumerable<T> objectlist
, string separator = ",", bool header = true)
{
FieldInfo[] fields = typeof(T).GetFields();
PropertyInfo[] properties = typeof(T).GetProperties();
if (header)
{
yield return String.Join(separator, fields
.Select(f => f.Name)
.Concat(properties.Select(p => p.Name))
.ToArray());
}
foreach (var o in objectlist)
{
yield return string.Join(separator, fields
.Select(f=>(f.GetValue(o) ?? "")
.ToString())
.Concat(properties
.Select(p=>(p.GetValue(o,null) ?? "").ToString())).ToArray());
}
}
And to produce the CSV file:
public class Person
{
public int IdPerson { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
var persons = new List<Person>
{
new Person(){IdPerson=1, FirstName = "FirstName, 1", LastName = "LastName 1" },
new Person(){IdPerson=2, FirstName = "FirstName/ 2", LastName = "LastName 2" },
new Person(){IdPerson=3, FirstName = "FirstName 3", LastName = "LastName 3" },
};
using (TextWriter tw = File.CreateText(@"D:\testoutput.csv"))
{
foreach (var line in ExcelExport.ToCsv(persons))
{
tw.WriteLine(line);
}
}
However, all my data nested in one column:
How is it possible to put the above data in different columns?