将XElement导出到Excel

假设我有以下列出的Log对象,并希望将列表导出到Excel。 我想将List<Log>转换为Excel。 我可以手动创build数据集,但有一个更聪明的方法?

 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 

由于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中获取值。