Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object entity to CSV serialization / conversion

Tags:

c#

.net

How can I write all values (properties) into an csv formated string in C#? e.g.:

class Person(string firstName, string lastName, int_age);
Person person = new Person("Kevin","Kline",33);

now I want a string "Kevin;Kline;33"

In other words I want to serialize an object into CSV

like image 568
uhu Avatar asked Jun 15 '12 12:06

uhu


3 Answers

Have a look at Josh Close's excellent CSVHelper library

var person = new Person("Kevin","Kline",33);
using (var csv = new CsvWriter(new StreamWriter("file.csv")))
{
    csv.Configuration.HasHeaderRecord = false;
    csv.Configuration.Delimiter = ';';
    csv.WriteRecord(person);
}

Output:

Kevin;Kline;33
like image 150
StuartLC Avatar answered Sep 28 '22 19:09

StuartLC


By using reflection you can retrieve the property infos from an object

foreach (PropertyInfo prp in obj.GetType().GetProperties()) {
   if (prp.CanRead) {
      object value = prp.GetValue(obj, null);
      string s = value == null ? "" : value.ToString();
      string name = prp.Name;
      ...
   }
} 

The GetProperties method has an overload accepting BindingFlags through which you can determine which kind of property you need, like private/public instance/static.

You can combine them like this

var properties = type.GetProperties(BindingFlags.Public | 
                                    BindingFlags.NonPublic | 
                                    BindingFlags.Instance);

Applied to your problem you could write

List<Person> people = ...;
Type type = typeof(Person);
PropertyInfo[] properties = type.GetProperties();
var sb = new StringBuilder();

// First line contains field names
foreach (PropertyInfo prp in properties) {
   if (prp.CanRead) {
      sb.Append(prp.Name).Append(';');
   }
}
sb.Length--; // Remove last ";"
sb.AppendLine();

foreach (Person person in people) {
    foreach (PropertyInfo prp in properties) {
       if (prp.CanRead) {
          sb.Append(prp.GetValue(person, null)).Append(';');
       }
    }
    sb.Length--; // Remove last ";"
    sb.AppendLine();
}

File.AppendAllText("C:\Data\Persons.csv", sb.ToString());

It is also a good idea to enclose strings in double quotes and to escape doubles quotes they contain by doubling them.

like image 25
Olivier Jacot-Descombes Avatar answered Sep 28 '22 18:09

Olivier Jacot-Descombes


you can use something like this:

...
        PropertyInfo[] properties = obj.GetType().GetProperties();
        string CSVRow = "";
        foreach (PropertyInfo pi in properties)
        {
            CSVRow = CSVRow + pi.GetValue(obj, null) + ";";
        }
        CSVRow.Remove(CSVRow.Length - 1, 1);
...
like image 2
M. X Avatar answered Sep 28 '22 19:09

M. X