2010-04-30 154 views
0

當我使用c#插入'\r\n'到word文檔中的表格單元格時,它不起作用,爲什麼?怎麼做 ?如何在Word中的表格單元格中插入換行符?

Word.Application wordApp; 
Word.Document wordDoc; 
filePath = @"" + strWorkPath + @"Uploads\Template\template.doc"; 
saveFilePath = @"" + strWorkPath + @"Uploads\" + VersionStr + @"\" + fileName; 
object format = Word.WdSaveFormat.wdFormatDocument; wordApp = new Word.Application(); 
Object nothing = Missing.Value; 
wordDoc = wordApp.Documents.Open(ref filePath, ref nothing, ref nothing, ref nothing, ref nothing,ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing); 
Word.Table table = wordDoc.Tables[1]; 
table.Cell(1, 1).Range.Text = "sdsdlkfjdslk \r\n slkdfjslj"; 

如最後一行所示。

在該文件中,它是"sdsdlkfjdslk \r\n slkdfjslj",不"sdsdlkfjdslk slkdfjslj"

回答

3

嘗試

"sdsdlkfjdslk" + (char)11 + "slkdfjslj" 

"sdsdlkfjdslk \v slkdfjslj" 
+0

+1這對我來說訣竅 – 2013-03-26 17:43:32

+0

對我來說,它會失敗,但有以下例外:'\ v',十六進制值0x0B,是一個無效字符。 – 2016-10-07 10:32:19

0

(炭)11和符\ v並沒有爲我工作。我收到「十六進制值0x0B,是一個無效字符」。以下解決方案爲我做了訣竅。

Paragraph paragraph = new Paragraph(); 
string[] lines = Value.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); 
Run run = new Run(new Text(lines[0])); 
if (lines.Length > 1) 
{ 
    run.AppendChild(new Break()); 
    run.AppendChild(new Text(lines[1])); 
} 
paragraph.Append(run); 

我最終保留了字符串,變量Value在示例中,以「\ n」作爲換行符進入單元格。我將字符串拆分爲換行符中的一個數組。我只有在代碼中有一次中斷的可能性,但如果有多個換行符,則可以使用foreach循環。

相關問題