2014-09-04 4 views
1

다음 목록이 Log 개이고 Excel로 목록을 내보내려고한다고 가정합니다. List<Log>을 (를) Excel로 변환하고 싶습니다. 수동으로 데이터 집합을 만들 수도 있지만 똑똑한 방법이 있습니까?XElement를 Excel로 내보내기

String xml1 = "<CustomerPricing><Id>673</Id><Customer>3</Customer><Code>XV1</Code><PricingType>20</PricingType><Discount>33</Discount><Company>10</Company></CustomerPricing>"; 
String xml2 = "<CustomerPricing><Id>674</Id><Customer>3</Customer><Code>XV1</Code><PricingType>30</PricingType><Discount>35</Discount><Company>10</Company></CustomerPricing>"; 

Log log1 = new Log { ModifiedBy = "user", DateModified = DateTime.Now, ChangedData = XElement.Parse(xml1) }; 
Log log2 = new Log { ModifiedBy = "user", DateModified = DateTime.Now, ChangedData = XElement.Parse(xml2) }; 

List<Log> logs = new List<Log> { log1, log2 }; 

등급 :

public class Log { 

    public DateTime DateModified { get; set; } 
    public String ModifiedBy { get; set; } 
    public XElement ChangedData { get; set; } 
} 

내 Excel 스프레드 시트가 (각 행)과 같이 보일 것이다 :

DateModified | ModifiedBy | CustomerPricing | Id | Customer | Code 
+0

OpenXML 방식 또는 Excel Interop을 사용하고 있습니까? –

+0

아직 시점이 아니지만 아이디어가 필요합니다. – PhillyNJ

+0

CSV 파일에 옵션을 덤프 할 수 있습니까? 그렇다면, 나는 당신을 위해 진정한 속삭임과 마른 대답을 얻었습니다. 그렇지 않다면 OpenXML을 사용한 최근 프로젝트를 파헤칩니다. –

답변

1

를 CSV가 충분하기 때문에, 여기에 덤프하는 빠른 방법 당신의 데이터 :

 using (var writer = new StreamWriter(@"C:\temp\yourfile.csv")) 
     { 
      string header = "DateModified,ModifiedBy,CustomerPricing,Id,Customer,Code"; 
      writer.WriteLine(header); 
      foreach (var log in logs) 
      { 
       string line = "\"" + log.DateModified.ToShortDateString() + "\",\"" + log.ModifiedBy + "\",\"" + 
           // you don't have a CustomerPricing element, as the whole object is CustomerPricing 
           // add a "Price" element and sub out the element value below 
           //log.ChangedData.Element("CustomerPricing").Value + "\",\"" + 
           log.ChangedData.Element("Id").Value + "\",\"" + 
           log.ChangedData.Element("Customer").Value + "\",\"" + 
           log.ChangedData.Element("Code").Value + "\""; 

       writer.WriteLine(line); 
      } 

     } 

오메 단점은있는 그대로입니다. 데이터에 이상한 문자가 있으면 CSV가 엉망이됩니다. CSV 라이브러리를 사용하여 깔끔하게 쓸 수 있습니다. .Element ("whatever") 메서드를 사용하여 XElement에서 값을 가져올 수 있습니다.