2010-05-26 136 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屬性嗎?