单元格中的Excel XML换行符

时间:2010-05-26 20:10:51

标签: c# excel linq-to-xml

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

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>

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

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

修改

好的 - 这是完全错误的,但帮助我获得了(我认为)有用的东西。如果你想嵌入一些否则会被XML渲染转义的东西,你需要将它嵌入CDATA块中。查看关于C#和XML的this related question,这会使我的记忆绊倒。

答案 1 :(得分:1)

不确定这是否有帮助,但以下代码:

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

生成此输出:

Foo$amp;#10;Bar

Foo&#10;Bar

因此,在使用newlineElement对象的代码中,您可以使用.Value属性吗?