Reputation: 38124
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?
Upvotes: 2
Views: 292
Reputation: 34160
Nothing is wrong with your csv, just excel does not recognize comma as separator. add this line as the first line of your csv file:
sep=,
and it will work fine.
Also, note that you have to wrap each item between double quotes to escape possible commas inside it and replace any double quote (inside text) with 2 double quotes to scape possible double quotes in the text:
yield return String.Join(separator,
fields.Select(f => $"\"{f.Name.Replace("\"","\"\"")}\"")
.Concat(properties.Select(p=>p.Name)).ToArray());
Upvotes: 3