Excel XML New row in cell

I am using LINQ to XML to create an Excel XML file . I want to include new rows in cells. Excel uses the literal 
 to represent a new line. If I try to add this using XText:

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

I get:

Foo
Bar

What is displayed in Excel as:

Foo
Bar

Is there any way to write to an XML file without doing

 String.Replace( "
", "
" ) 

by the resulting text file?

EDIT Here is a code snippet showing how I create a line for an Excel document. I avoided this as it is a bit dirty. :) Let me know if more code helps, or if it just adds more confusion.

In this example, the newlineElement described above newlineElement represented by a single XText in the sample code.

 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 ) ); 

This gives:

  <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> 

Thanks for the help so far!

+7
c # excel linq-to-xml
source share
2 answers

insert the actual character into the string, not the escape code. LINQ will handle the conversion for you.

EDIT:

Well - that was completely wrong, but it helped me get what (I think) works. If you want to embed something that otherwise would be escaped by XML rendering, you need to embed it in a CDATA block. Mark this related question in C # and the XML that disabled my memory.

+1
source share

Not sure if this helps, but the following code:

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

Produces this conclusion:

Foo$amp;#10;Bar

Foo&#10;Bar

So, in your code that uses the newlineElement object, can you use the .Value property?

+1
source share

All Articles