在C#中将数据对象导入/导出为CSV

时间:2013-12-23 14:14:00

标签: c# csv serialization export

是否有任何组件可以获取数据对象,并根据某些规则通过反射将其输出为CSV格式?

例如,采用以下数据结构:

Member
------
Name : string
Surname : string                         
ContactDetails : ContactDetails

ContactDetails
--------------
Address1 : string
Address2 : string
City : string
Telephone : string

如果必须将Member导出为CSV,则会产生以下几列:

  • 名称
  • ContactDetails.Address1
  • ContactDetails.Address2
  • ContactDetails.City
  • ContactDetails.Telephone

这也可以反向完成,CSV文件通过反射转换回数据对象。

1 个答案:

答案 0 :(得分:1)

好的,这就是我要在反射上创建CSV库的方法。我会将对象序列化为XML,然后使用XSLT将生成的XML转换为CSV:

 namespace ConsoleApplication1
    {
       [XmlRoot(ElementName = "Players")] 
        public class Players : System.Collections.Generic.List<Player> {
            public Players() { }
        }

       public class Player{
       public string Name { get; set; }
           public string Team { get; set; } 
           public string Position { get; set; }
           public Player(string name, string position, string team) {
               this.Name = name;
               this.Position = position;
               this.Team = team;
           }
           public Player() { }
       }


        [System.Runtime.InteropServices.GuidAttribute("D36900FE-8902-4ED8-B961-DE5B3F3273AC")]
        class Program
        {
            static void Main(string[] args)
            {
                Players players= new Players();
                players.Add(new Player("C.Ronaldo", "Man Utd", "Midfielder"));
                XmlSerializer ser = new XmlSerializer(typeof(Players));
                var writer = new System.IO.StreamWriter(@"C:\myxml.xml", false);
                ser.Serialize(writer, players);
                writer.Flush();
                writer.Close();            
                var myXslTrans = new XslCompiledTransform();
                myXslTrans.Load(@"C:\CSV.xslt", null, null );            
                myXslTrans.Transform(@"file://C:/myxml.xml", @"C:\converted.csv"); 
            }
        }
    }

这是我的示例XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:telerik="remove" xmlns:asp="remove">
    <xsl:template match="/">        
    <xsl:for-each select="Players/Player">
        <xsl:value-of select="Name" />,<xsl:value-of select="Team" />,<xsl:value-of select="Position" />
    </xsl:for-each>     
    </xsl:template>
</xsl:stylesheet>

声明:

  I know the XSLT needs break lines or may need additional formats. I only intent to describe a possible path to CSV/Reflection and not a fully working solution.