我对编程世界还很陌生,所以这个问题可能很愚蠢,但我被困住了,希望得到一些帮助。
我正在使用 XDocument 更改信息并将其添加到 Excel 工作表(这是一个 XML 文档),以便从 Autodesk Revit 获取 Excel 报告。 工作表文档由工作表信息组成,包括此配置中的行和单元格:
<row r="11" spans="1:11" x14ac:dyDescent="0.2">
<c r="A11" s="198" t="inlineStr">
<is>
<t>example</t>
</is>
</c>
<c r="B11" s="199" t="inlineStr">
<is>
<t>string</t>
</is>
</c>
<c r="C11" s="200"/>
<c r="D11" s="201"/>
<c r="E11" s="201"/>
<c r="F11" s="202"/>
<c r="G11" s="203"/>
<c r="H11" s="204"/>
<c r="I11" s="205"/>
<c r="J11" s="205"/>
<c r="K11" s="206"/>
</row>
代码的相关部分位于行元素中。 spans-attribute 的值为“1:11”,这就是我的问题所在。它不允许我输入“:”字符作为属性的值。我在网上搜索过,发现它与此链接中的命名空间声明有关: "The ':' character, hexadecimal value 0x3A, cannot be included in a name"
但是,将“:”字符放入属性值中对于 Excel 文档的工作至关重要。我按如下方式创建行元素:
XElement row = new XElement("row",
new XAttribute("r", i.ToString()),
new XAttribute("spans", "1:" + collumnCount.ToString()),
new XAttribute("x14ac:dyDescent", "0.2"));
我不明白为什么它不允许我将“:”放入 XAttribute 的值中,因为这只是一个字符串。有什么办法可以做到这一点吗?
我尝试使用 XMLDocument 将字符串“1:11”添加到 XMLAttribute。这确实有效,但我不敢相信 XDocument 不可能做到这一点。
提前致谢
最佳答案
您应该在元素名称中包含 :。现在已经允许了。如果您看到有人这样做,那么 : 不是元素名称的一部分,它是命名空间和元素名称之间的分隔符。所以为了得到如下的XML文件:
<rss xmlns:media="http://m.xyz.com/rss/" version="2.0">
<channel vendor="ABC" lastpublishdate="05/12/2013 01:02"/>
<title>Videos</title>
<media:thumbnail width="180" height="75" />
</rss>
你必须写这样的东西:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string x = "55";
XNamespace aw = "http://m.xyz.com/rss/";
XDocument document = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement(
"rss",
new XAttribute(XNamespace.Xmlns + "media", "http://m.xyz.com/rss/"),
new XAttribute("version", "2.0"),
new XElement("channel",
new XAttribute("vendor", "ABC"),
new XAttribute("lastpublishdate", DateTime.Now.ToString("dd/MM/yyyy hh:mm"))),
new XElement("title", "Videos"),
new XElement(
aw + "thumbnail",
new XAttribute("width", x.Trim()),
new XAttribute("height", x.Trim())
)
)
);
}
}
}
关于excel - 在 XDocument 中使用 ':' 字符生成 Excel - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13949707/