gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:55:54 24 4
gpt4 key购买 nike

我试图只将查询的结果集写入 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;
}

最佳答案

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 ("▪", "");

关于linqpad - 将 LinqPAD 结果导出到没有行数元数据的 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15169612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com