有没有快速的方法将实体转换为.csv文件?

时间:2010-07-07 23:09:07

标签: c# entity-framework object csv entity

目前,我有:

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

我还是实体框架的新手,有更快的方法吗?

3 个答案:

答案 0 :(得分:24)

示例代码,显示了一种简单而强大的方法来完成您想要的内容而无需硬编码属性名称(使用反射):

 /// <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();
 }

更多相关内容:

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

答案 1 :(得分:5)

我接受了Leniel的建议并将其整理成一个功能齐全的“作家”,它还允许您过滤您想要写的属性。以下是您的使用代码:

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();
    }
}

答案 2 :(得分:0)

string csv = "";
//get property names from the first object using reflection    
IEnumerable<PropertyInfo> props = entityObjects.First().GetType().GetProperties();

//header 
csv += String.Join(", ",props.Select(prop => prop.Name)) + "\r\n";

//rows
foreach(var entityObject in entityObjects) 
{ 
    csv += String.Join(", ", props.Select(
        prop => ( prop.GetValue(entityObject, null) ?? "" ).ToString() 
    ) )
    + "\r\n";
}
  • 最好将StringBuilder用于许多实体
  • 代码不检查实体对象何时为空