将具有嵌套属性和值的导出对象导出到csv

时间:2012-04-12 05:33:06

标签: c# properties csv export

我正在努力将具有嵌套属性(对象)的对象导出到csv文件。

这里是代码:

    /// <summary>
    /// Exports a CSV
    /// </summary>
    /// <param name="csv">The CSV data as a string</param>
    /// <param name="filename">The filename for the exported file</param>
    public static void ExportCSV(string csv, string filename)
    {
        StreamWriter writer = new StreamWriter(filename);
        try
        {
            writer.Write(csv);
        }
        catch (FileNotFoundException ex)
        {
            throw ex;
        }
        finally
        {
            writer.Close();
        }
    }

    /// <summary>
    /// Generate the CSV data as a string using reflection on the objects in the list
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list">The generic list</param>
    /// <returns></returns>
    public static string GetCSV<T>(this List<T> list)
    {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < list.Count; i++)
        {
            sb.AppendLine(GetPropertiesString<T>(list[i]));
        }

        return sb.ToString();
    }


    public static string GetPropertiesString<T>(T item)
    {
        StringBuilder sb = new StringBuilder();
        PropertyInfo[] propInfos = typeof(T).GetProperties();

        for (int i = 0; i <= propInfos.Length - 1; i++)
        {
            Type propertyType = propInfos[i].PropertyType;

            if (propertyType != typeof(string) && propertyType != typeof(int) && propertyType != typeof(double) && propertyType != typeof(float) && propertyType != typeof(decimal))
            {
                string test = GetPropertiesString(propertyType);
            }

            sb.Append(propInfos[i].Name);

            if (i < propInfos.Length - 1)
            {
                sb.Append(",");
            }
        }

        sb.AppendLine();

        for (int j = 0; j <= propInfos.Length - 1; j++)
        {
            object o = item.GetType().GetProperty(propInfos[j].Name).GetValue(item, null);

            if (o != null)
            {
                string value = o.ToString();

                //Check if the value contans a comma and place it in quotes if so
                if (value.Contains(","))
                {
                    value = string.Concat("\"", value, "\"");
                }

                //Replace any \r or \n special characters from a new line with a space
                if (value.Contains("\r"))
                {
                    value = value.Replace("\r", " ");
                }
                if (value.Contains("\n"))
                {
                    value = value.Replace("\n", " ");
                }

                sb.Append(value);
            }

            if (j < propInfos.Length - 1)
            {
                sb.Append(",");
            }
        }

        return sb.ToString();
    }
}

}

这是我的对象

/// <summary>
/// Basic Person object
/// </summary>
public class Person
{
    public string Forename { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
    public Adress Adress { get; set; }
}

public class Adress
{
    public string Place { get; set; }
    public int PLZ { get; set; }
}

所需的csv文件格式:

header: Forename, Surename, Age, Place, PLZ 
values: Joe, Stevens, 30,Town1, 11111

我试着递归调用该方法,但是那么PropertyInfo [] propInfos = typeof(T).GetProperties()的结果有奇怪的项目吗?

应该可以导出任何嵌套对象深的对象。

有什么建议吗?

感谢, 的Thorsten

1 个答案:

答案 0 :(得分:0)

您的代码无法正常工作,因为您没有使用正确的类型递归调用该方法。

GetPropertiesString(propertyType);

应该像这样调用:

dynamic ob = Activator.CreateInstance(propertyType);
string test = GetPropertiesString(ob);