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

前端 未结 3 1353
一生所求
一生所求 2021-02-03 12:28

at present, I have:

        string outputRow = string.Empty;
        foreach (var entityObject in entityObjects)
        {
            outputRow = entityObject.f         


        
3条回答
  •  温柔的废话
    2021-02-03 12:44

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

     /// 
     /// Creates a comma delimeted string of all the objects property values names.
     /// 
     /// object.
     /// string.
     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

提交回复
热议问题