Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 818
KevinDeus Avatar asked Jul 07 '10 23:07

KevinDeus


People also ask

How do I convert Excel to CSV file?

You can convert an Excel worksheet to a text file by using the Save As command. Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited).

How do I convert a File to CSV?

In your Excel workbook, switch to the File tab, and then click Save As. Alternatively, you can press F12 to open the same Save As dialog. 2. In the Save as type box, choose to save your Excel file as CSV (Comma delimited).

What is a CSV conversion?

CSV, sometimes known as a comma separated values file is commonly used by spreadsheet applications. It allows plain text data to be saved in tabular format. If a user has a large volume of data and needs to transfer it between applications then a CSV file is often used.


2 Answers

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

like image 84
Leniel Maccaferri Avatar answered Oct 17 '22 17:10

Leniel Maccaferri


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();
    }
}
like image 39
mBria Avatar answered Oct 17 '22 17:10

mBria