2009-04-08 127 views
5

IM目前使用這樣的事情在單元格中插入聯字符串:如何在OPENXML電子表格單元格中插入換行符?

new Cell() 
{ 
    CellReference = "E2", 
    StyleIndex = (UInt32Value)4U, 
    DataType = CellValues.InlineString, 
    InlineString = new InlineString(new Text("some text")) 
} 

\n不起作用插入斷行,我怎麼能這樣做呢?

感謝


響應

new Cell(
     new CellValue("string \n string") 
     ) 
    { 
     CellReference = "E2", 
     StyleIndex = (UInt32Value)4U, 
     DataType = CellValues.String   
    } 

回答

4

嘗試CellValues.String而不是CellValues.InlineString。

8

你需要做兩件事情:

1)標記細胞爲「換行文本」。如果您使用現有電子表格作爲模板,則可以手動在電子表格中執行此操作。只需右鍵單擊單元格並選擇「Format Cells ..」,單擊「Alignment」選項卡並選中「Wrap Text」複選框。
或...您可以通過編程方式設置CellFormat。如果你有一個名爲「CF」一個CellFormat對象,你會做這樣的事情:

cf.ApplyAlignment = true;//Set this so that Excel knows to use it. 
if (cf.Alignment == null)//If no pre-existing Alignment, then add it. 
    cf.Alignment = new Alignment() { WrapText = true }; 
Alignment a = cf.Alignment; 
if (a.WrapText == null || a.WrapText.Value == false) 
    a.WrapText = new BooleanValue(true);//Update pre-existing Alignment. 

2)你不應該使用「\ n」,而不是你應該使用標準回車換行+換行組合:「\ r \ n」
如果您正在混合兩個(即「\ n」而沒有前面的「\ r」和「\ r \ n」),則應該修復它在填充單元格值之前:

sHeaderText = sHeaderText.Replace("\r\n", "\n").Replace("\n", "\r\n"); 

我,我自己,不要使用CellValues.String甚至CellValues.InlineString
相反,我使用CellValues.SharedString(就像Excel一樣)構建我的文本單元格。
對於Bool,我使用「10 CellValues.Boolean」,對於所有其他人(數字和日期),我不將單元格的DataType設置爲任何值 - 因爲這是Excel在查看它創建的標記時所做的。

+0

如何將`CellFormat`對象或`Alignment`對象應用於給定的單元格? – Panzercrisis 2017-08-22 16:19:07

相關問題