Is there a quick way to convert an entity to .csv file?

15,668

Solution 1

Sample code that shows a simple yet powerful way of accomplishing what you want with no need to hard code property names (using reflection):

 /// <summary>
 /// Creates a comma delimeted string of all the objects property values names.
 /// </summary>
 /// <param name="obj">object.</param>
 /// <returns>string.</returns>
 public static string ObjectToCsvData(object obj)
 {
     if (obj == null)
     {
         throw new ArgumentNullException("obj", "Value can not be null or Nothing!");
     }
  
     StringBuilder sb = new StringBuilder();
     Type t = obj.GetType();
     PropertyInfo[] pi = t.GetProperties();
  
     for (int index = 0; index < pi.Length; index++)
     {
         sb.Append(pi[index].GetValue(obj, null));
  
         if (index < pi.Length - 1)
         {
            sb.Append(",");
         }
     }
  
     return sb.ToString();
 }

More on this:

Objects to CSV

How can i convert a list of objects to csv

Are there any CSV readers/writer lib’s in c#

Writing a CSV file in .net

LINQ to CSV : Getting data the way you want

LINQ to CSV library

Solution 2

I took Leniel's suggestion and wrapped it up in a full featured "writer" that also allows you to filter the properties you want written. Here's the code for your usage:

public class CsvFileWriter
{
    public static void WriteToFile<T>(string filePath, List<T> objs, string[] propertyNames)
    {
        var builder = new StringBuilder();
        var propertyInfos = RelevantPropertyInfos<T>(propertyNames);
        foreach (var obj in objs)
            builder.AppendLine(CsvDataFor(obj, propertyInfos));

        File.WriteAllText(filePath, builder.ToString());
    }

    public static void WriteToFileSingleFieldOneLine<T>(string filePath, List<T> objs, string propertyName)
    {
        var builder = new StringBuilder();
        var propertyInfos = RelevantPropertyInfos<T>(new[] { propertyName });
        for (var i = 0; i < objs.Count; i++)
        {
            builder.Append(CsvDataFor(objs[i], propertyInfos));

            if (i < objs.Count - 1)
                builder.Append(",");
        }

        File.WriteAllText(filePath, builder.ToString());
    }

    private static List<PropertyInfo> RelevantPropertyInfos<T>(IEnumerable<string> propertyNames)
    {
        var propertyInfos = typeof(T).GetProperties().Where(p => propertyNames.Contains(p.Name)).ToDictionary(pi => pi.Name, pi => pi);
        return (from propertyName in propertyNames where propertyInfos.ContainsKey(propertyName) select propertyInfos[propertyName]).ToList();
    }

    private static string CsvDataFor(object obj, IList<PropertyInfo> propertyInfos)
    {
        if (obj == null)
            return "";

        var builder = new StringBuilder();

        for (var i = 0; i < propertyInfos.Count; i++)
        {
            builder.Append(propertyInfos[i].GetValue(obj, null));

            if (i < propertyInfos.Count - 1)
                builder.Append(",");
        }

        return builder.ToString();
    }
}
Share:
15,668
KevinDeus
Author by

KevinDeus

C# JQuery nunit WCF Subversion SharpSVN TFS RoombaSCI CreateOI Framework ChessMangler

Updated on July 15, 2022

Comments

  • KevinDeus
    KevinDeus almost 2 years

    at present, I have:

            string outputRow = string.Empty;
            foreach (var entityObject in entityObjects)
            {
                outputRow = entityObject.field1 + "," + entityObject.Field2  etc....
            }
    

    I'm still new to the Entity Framework, is there a quicker way?

  • Sam
    Sam about 5 years
    Will fail if any of your properties contains a ,
  • Brandon Osborne
    Brandon Osborne about 3 years
    @Sam That's true, but if you just add a .Replace(",", "&comma;") or similar construct to the model you'll be fine. Even replacing with chr(",") will do the trick.