Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a list of objects to csv?

If I have a list of objects called "Car":

public class Car
{
     public string Name;
     public int Year;
     public string Model;
}

How do I convert a list of objects, e.g. List<Car> to a csv?

like image 280
leora Avatar asked Feb 21 '10 17:02

leora


2 Answers

  1. FileHelpers Library
  2. Text OleDb Provider
  3. Manual via String concatenation according to RFC-4180
  4. Third party library, for example Aspose.Cells can do it without any friction from you. And it is very fast.
like image 87
Sergey Mirvoda Avatar answered Oct 01 '22 13:10

Sergey Mirvoda


add the following method to Car:

String Escape(String s)
{
    StringBuilder sb = new StringBuilder();
    bool needQuotes = false;
    foreach (char c in s.ToArray())
    {
        switch (c)
        {
            case '"': sb.Append("\\\""); needQuotes = true; break;
            case ' ': sb.Append(" "); needQuotes = true; break;
            case ',': sb.Append(","); needQuotes = true; break;
            case '\t': sb.Append("\\t"); needQuotes = true; break;
            case '\n': sb.Append("\\n"); needQuotes = true; break;
            default: sb.Append(c); break;
        }
    }
    if (needQuotes)
        return "\"" + sb.ToString() + "\"";
    else
        return sb.ToString();
}

public void SerializeAsCsv(Stream stream)
{
    stream.Write(Escape(Name));
    stream.Write(",");
    stream.Write(Year.ToString());
    stream.Write(",");
    stream.Write(Escape(Model));
    stream.Write("\n");
}

Now you can serialize the whole list:

foreach (Car car in list)
{
    car.SerializeAsCsv(stream);
}
like image 30
Vlad Avatar answered Oct 01 '22 15:10

Vlad