对象实体到CSV序列化/转换

时间:2012-06-15 12:49:48

标签: c# .net

如何在C#中将所有值(属性)写入csv格式化字符串? e.g:

class Person(string firstName, string lastName, int_age);
Person person = new Person("Kevin","Kline",33);

现在我想要一个字符串“Kevin; Kline; 33”

换句话说,我想将对象序列化为CSV

6 个答案:

答案 0 :(得分:13)

查看Josh Close's优秀的CSVHelper

var person = new Person("Kevin","Kline",33);
using (var csv = new CsvWriter(new StreamWriter("file.csv")))
{
    csv.Configuration.HasHeaderRecord = false;
    csv.Configuration.Delimiter = ';';
    csv.WriteRecord(person);
}

输出:

Kevin;Kline;33

答案 1 :(得分:9)

通过使用反射,您可以从对象中检索属性信息

foreach (PropertyInfo prp in obj.GetType().GetProperties()) {
   if (prp.CanRead) {
      object value = prp.GetValue(obj, null);
      string s = value == null ? "" : value.ToString();
      string name = prp.Name;
      ...
   }
} 

GetProperties方法有一个重载接受BindingFlags,您可以通过它来确定所需的属性,例如私有/公共实例/静态。

你可以像这样组合它们

var properties = type.GetProperties(BindingFlags.Public | 
                                    BindingFlags.NonPublic | 
                                    BindingFlags.Instance);

适用于您的问题,您可以写

List<Person> people = ...;
Type type = typeof(Person);
PropertyInfo[] properties = type.GetProperties();
var sb = new StringBuilder();

// First line contains field names
foreach (PropertyInfo prp in properties) {
   if (prp.CanRead) {
      sb.Append(prp.Name).Append(';');
   }
}
sb.Length--; // Remove last ";"
sb.AppendLine();

foreach (Person person in people) {
    foreach (PropertyInfo prp in properties) {
       if (prp.CanRead) {
          sb.Append(prp.GetValue(person, null)).Append(';');
       }
    }
    sb.Length--; // Remove last ";"
    sb.AppendLine();
}

File.AppendAllText("C:\Data\Persons.csv", sb.ToString());

将字符串括在双引号中并通过将它们加倍来转义它们包含的双引号也是一个好主意。

答案 2 :(得分:2)

你可以使用这样的东西:

...
        PropertyInfo[] properties = obj.GetType().GetProperties();
        string CSVRow = "";
        foreach (PropertyInfo pi in properties)
        {
            CSVRow = CSVRow + pi.GetValue(obj, null) + ";";
        }
        CSVRow.Remove(CSVRow.Length - 1, 1);
...

答案 3 :(得分:2)

我相信FileHelpers对此有好处,我自己并没有在愤怒中使用它

答案 4 :(得分:0)

这样的事情:

public string ToCsv()
{
    return string.Join(";", new string[]{
        _firstName,
        _lastName,
        _age.ToString()
    }.Select(str=>Escape(str)));
}

或者,使用反射,

public static string ToCsv(this object obj)
{
    return string.Join(";",
        this.GetType().GetProperties().Select(pi=>
            Escape(pi.GetValue(this, null).ToString())
        ));
}

Escape是一个合适的转义函数。

答案 5 :(得分:0)

一种可能的实现,即读取复杂对象(深层对象序列化),如具有属性对象数组的对象数组,并保存一个格式为CSV文件的字符串:

private string ToCsv(string separator, IEnumerable<object> objectList)
{
    StringBuilder csvData = new StringBuilder();
    foreach (var obj in objectList)
    {
        csvData.AppendLine(ToCsvFields(separator, obj));
    }
    return csvData.ToString();
}

private string ToCsvFields(string separator, object obj)
{
    var fields = obj.GetType().GetProperties();
    StringBuilder line = new StringBuilder();

    if (obj is string)
    {
        line.Append(obj as string);
        return line.ToString();
    }

    foreach (var field in fields)
    {
        var value = field.GetValue(obj);
        var fieldType = field.GetValue(obj).GetType();

        if (line.Length > 0)
        {
            line.Append(separator);
        }
        if (value == null)
        {
            line.Append("NULL");
        }
        if (value is string)
        {
            line.Append(value as string);
        }
        if (typeof(IEnumerable).IsAssignableFrom(fieldType))
        {
            var objectList = value as IEnumerable;
            StringBuilder row = new StringBuilder();

            foreach (var item in objectList)
            {
                if (row.Length > 0)
                {
                    row.Append(separator);
                }
                row.Append(ToCsvFields(separator, item));
            }
            line.Append(row.ToString());
        }
        else
        {
            line.Append(value.ToString());
        }
    }
    return line.ToString();
}