2010-05-26 150 views
7

我正在使用LINQ to XML来创建Excel XML文件。我想在单元格中包含换行符。 Excel使用
文字表示新行。如果我尝试添加该使用XTEXT:单元格中的Excel XML换行符

XText newlineElement = new XText("Foo
Bar"); 

我得到:

Foo
Bar

在Excel其中显示为:

Foo
Bar

有没有一种办法将&#10写入XML文件而不做

String.Replace("
", "
") 

生成的文件文本?

编辑这里是一段代码片段,展示了如何为Excel文档创建一行。由于它有点混乱,我避免了它。 :)让我知道如果更多的代码会有所帮助,或者如果这只会增加更多的困惑。

在此示例中,上述newlineElement由代码示例中唯一的XText表示。

const string CELL = "{urn:schemas-microsoft-com:office:spreadsheet}Cell"; 
const string DATA = "{urn:schemas-microsoft-com:office:spreadsheet}Data"; 
const string STYLE = "{urn:schemas-microsoft-com:office:spreadsheet}StyleID"; 
const string TYPE= "{urn:schemas-microsoft-com:office:spreadsheet}Type"; 
const string HEIGHT = "{urn:schemas-microsoft-com:office:spreadsheet}Height"; 
const string ROW = "{urn:schemas-microsoft-com:office:spreadsheet}Row"; 

...

XElement rowElement = new XElement(Row, 
            new XElement(CELL, 
             new XAttribute(STYLE, "s0")), 
            new XElement(CELL, 
             new XElement(DATA, 
              new XText(description.Replace("\n", "
")), 
              new XAttribute(TYPE, "String")), 
             new XAttribute(STYLE, "sWrap")), 
            new XElement(CELL, 
             new XAttribute(STYLE, "s0")), 
            new XAttribute(HEIGHT, height)); 

这将产生:

<ss:Row ss:Height="45"> 
    <ss:Cell ss:StyleID="s0" /> 
    <ss:Cell ss:StyleID="sWrap"> 
     <ss:Data ss:Type="String">Foo&amp;#10;Bar</ss:Data> 
    </ss:Cell> 
    <ss:Cell ss:StyleID="s0" /> 
    </ss:Row> 

感谢您的帮助迄今!

+0

相信与否,这似乎不可能。 – SLaks 2010-05-26 20:20:20

+0

您可以发布一些示例代码,了解它如何进入Excel文件? – CoderDennis 2010-05-26 23:34:50

+0

基本上,看到一些代码在创建后显示如何使用newlineElement对象会很好。 – CoderDennis 2010-05-26 23:44:49

回答

1

将实际字符插入字符串而不是转义码 - LINQ将为您处理转换。

编辑:

好了 - 这是完全错误的,但是帮助我得到一些东西,(我认为)的作品。如果你想嵌入一些本来可以被XML渲染转义的东西,你需要将它嵌入到CDATA块中。查看关于C#和XML的this related question,这些内容触发了我的记忆。

+0

我不认为会。 – SLaks 2010-05-26 20:15:27

+0

我认为你可以使用“\ n”插入内联。 – 2010-05-26 20:16:00

+0

它不会。我尝试过这个。 – SLaks 2010-05-26 20:17:21

1

不知道这是否会有所帮助,但下面的代码:

var newlineElement = new XText("Foo&#10;Bar"); 
Console.WriteLine(newlineElement); 
Console.WriteLine(newlineElement.Value); 

产生这样的输出:

Foo$amp;#10;Bar

Foo&#10;Bar

所以,在你的代码,该代码使用newlineElement对象,你可以使用.Value属性吗?