2013-12-23 109 views
2

是否有任何組件會根據某些規則將數據對象接收並通過反射將其輸出爲CSV格式?將數據對象導入/導出爲C#中的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

好吧,這是我會做什麼來創建反思基礎的CSV。我想序列化對象到XML,然後將生成的XML使用XSLT轉換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.