【问题标题】:export object with nested properties and values to csv将具有嵌套属性和值的对象导出到 csv
【发布时间】:2012-04-12 15:01:29
【问题描述】:

我正在努力将具有嵌套属性(对象)的对象导出到 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()的结果有奇怪的项目??

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

有什么建议吗?

谢谢, 托尔斯滕

【问题讨论】:

    标签: c# properties csv export


    【解决方案1】:

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

    GetPropertiesString(propertyType);
    

    应该这样称呼:

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

    【讨论】:

    • 嗨,谢谢。我试过你的例子但没有成功。如何检查该属性是否为嵌套对象。目前我用一个简单的 if(propertyType != typeof(string)) 检查它,但我认为这不正确或不方便。
    • 问题是您使用 System.Type 调用 GetPropertiesString ,这就是您获得其他属性的原因。因此,用我的代码替换该代码并尝试使用调试器来查看您将获得嵌套类型属性。不过,您的代码有几个问题,因为当您递归调用该方法时,您会重新实例化您的 StringBuilder,因此您会丢失以前的结果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    相关资源
    最近更新 更多