2013-03-02 20 views
3

我試圖寫一個excel文件,只是查詢的結果集,但我不斷得到行數的頭列,這弄亂了我需要的後續數據處理去做。我可以導入導出的文件並刪除第一行,但如果我可以導出沒有標題行的數據集,情況會好得多。將LinqPAD結果導出到沒有rowcount元數據的Excel文件中

這是我的黑客,我想知道是否有人有更好的方式來做到這一點。我正在生成的HTML,並使用正則表達式來猛拉出來的標題行:

public string DumpToHtmlString<T>(T objectToSerialize, string filePath) 
    { 
     string strHTML = "", outpuWithoutHeader =""; 
     try 
     { 
      var writer = LINQPad.Util.CreateXhtmlWriter(true); 
      writer.Write(objectToSerialize); 
      strHTML = writer.ToString(); 
      outpuWithoutHeader = Regex.Replace(strHTML, "<tr><td class=\"typeheader\"((\\s*?.*?)*?)<\\/(tr|TR)>", "", RegexOptions.Multiline); 
      System.IO.File.WriteAllText(filePath, outpuWithoutHeader); 

     } 
     catch (Exception exc) 
     { 
      Debug.Assert(false, "Investigate why ?" + exc); 
     } 
     return outpuWithoutHeader; 
    } 

回答

6

是對objectToSerialize一個IEnumerable?如果是這樣,LINQPad betaWriteCsv方法,其目的是創建於Excel的CSV文件:

Util.WriteCsv(data, @"c:\temp\results.csv"); 

否則,你是更安全的使用LINQ到XML DOM修改的輸出,而不是正則表達式。以下代碼說明了如何從LINQPad輸出中刪除格式。您可以調整它以刪除標題和彙總:

XDocument doc = XDocument.Load (...); 
XNamespace xns = "http://www.w3.org/1999/xhtml"; 

doc.Descendants (xns + "script").Remove(); 
doc.Descendants (xns + "span").Where (el => (string)el.Attribute ("class") == "typeglyph").Remove(); 

doc.Descendants().Attributes ("style").Where (a => (string)a == "display:none").Remove(); 

doc.Descendants (xns + "style").Remove(); 
doc.Descendants (xns + "tr").Where (tr => tr.Elements().Any (td => (string)td.Attribute ("class") == "typeheader")).Remove(); 
doc.Descendants (xns + "i").Where (e => e.Value == "null").Remove(); 

foreach (XElement anchor in doc.Descendants (xns + "a").ToArray()) 
    anchor.ReplaceWith (anchor.Nodes()); 

var presenters = doc.Descendants (xns + "table") 
    .Where (el => (string)el.Attribute ("class") == "headingpresenter") 
    .Where (e => e.Elements().Count() == 2) 
    .ToArray(); 

foreach (var p in presenters) 
{ 
    var heading = p.Elements().First().Elements(); 
    var content = p.Elements().Skip (1).First().Elements(); 

    if (stripFormatting) 
     p.ReplaceWith (heading, new XElement (xns + "p", content)); 
    else 
     p.ReplaceWith (
      new XElement (xns + "br"), 
      new XElement (xns + "span", new XAttribute ("style", "color: green; font-weight:bold; font-size: 110%;"), heading), 
      content); 
} 

// Excel centre-aligns th even if the style says otherwise. So we replace them with td elements. 
foreach (var th in doc.Descendants (xns + "th")) 
{ 
    th.Name = xns + "td"; 
    if (!stripFormatting && th.Attribute ("style") == null) 
     th.Add (new XAttribute ("style", "font-weight: bold; background-color: #ddd;")); 
} 

string finalResult = doc.ToString().Replace ("Ξ", "").Replace ("▪", ""); 
+0

是的,它是IEnumerable。謝謝。 – BraveNewMath 2013-03-04 20:21:19

+0

儘管xml操作比正則表達式更詳細。 – BraveNewMath 2013-03-04 20:31:56