2010-07-07 36 views
9

hiện nay, tôi có:Có cách nào nhanh chóng để chuyển đổi thực thể thành tệp .csv không?

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

Tôi vẫn còn mới đến khung Entity, là có một cách nhanh hơn?

+0

Có vẻ giống như câu trả lời, tất cả đều sử dụng sự phản chiếu. Tôi muốn tò mò về bất kỳ cách nào để làm điều này mà không phản ánh? Tôi đoán nó có thể là không thể mặc dù. –

+0

Bạn có thể thử trình soạn thảo tập tin có trọng số rất nhẹ của mình: https://gist.github.com/eranbetzalel/5371817#file-delimitedfilewriter-cs –

Trả lời

22
đang

mẫu cho thấy một cách đơn giản nhưng mạnh mẽ của việc hoàn thành những gì bạn muốn mà không cần phải tên thuộc tính cứng mã (sử dụng phản ánh):

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

Thông tin thêm về điều này:

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

4

tôi đã gợi ý Leniel và bọc nó trong một đầy đủ tính năng "nhà văn" mà cũng cho phép bạn lọc các thuộc tính bạn muốn viết. Dưới đây là đoạn code để sử dụng của bạn:

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(); 
    } 
} 
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"; 
} 
  • sẽ được tốt hơn để sử dụng StringBuilder cho nhiều entitys
  • Mã này không kiểm tra khi entityObjects trống
Các vấn đề liên quan