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

本文关键字:转换 序列化 CSV 实体 对象 | 更新日期: 2023-09-27 18:37:14

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

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

现在我想要一个字符串"凯文;克莱恩;33"

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

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

看看 Josh Close 优秀的 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

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

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

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

你可以使用这样的东西:

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

FileHelpers对此有好处,不过我自己并没有生气地使用它

像这样:

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

其中转义是适当的转义功能。

一种可能的实现,读取复杂对象(深层对象序列化),例如具有对象数组属性的对象数组,并保存格式为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();
}