将LinqPAD结果导出到没有rowcount元数据的Excel文件

时间:2013-03-02 01:27:05

标签: linqpad

我试图将一个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;
    }

1 个答案:

答案 0 :(得分:6)

objectToSerialize是IEnumerable吗?如果是这样,LINQPad beta有一个WriteCsv方法,用于创建Excel友好的CSV文件:

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

否则,使用LINQ-to-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 ("▪", "");