【问题标题】:Is there a quick way to convert an entity to .csv file?有没有快速将实体转换为 .csv 文件的方法?
【发布时间】:2011-03-13 02:13:08
【问题描述】:

目前,我有:

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

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

【问题讨论】:

  • 看起来答案都使用反射。我很好奇没有反思的任何方式吗?我猜这可能是不可能的。
  • 你可以试试我的轻量级分隔文件编写器:gist.github.com/eranbetzalel/…

标签: c# entity-framework object csv entity


【解决方案1】:

示例代码展示了一种简单而强大的方式来完成您想要的事情,而无需对属性名称进行硬编码(使用反射):

 /// <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

【讨论】:

  • 如果您的任何属性包含 , 将失败
  • @Sam 没错,但如果你只是在模型中添加一个 .Replace(",", "&comma;") 或类似的构造,你会没事的。即使用 chr(",") 替换也可以解决问题。
【解决方案2】:

我采纳了 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();
    }
}

【讨论】:

    【解决方案3】:
    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 会更好
    • 代码不检查 entityObjects 何时为空

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 2023-01-05
      • 2021-01-03
      • 2019-11-30
      • 2019-03-31
      • 2020-12-01
      相关资源
      最近更新 更多