Charles
Charles

Reputation: 11

How to Insert a Newline into a Table Cell in Word?

when i insert '\r\n' into a cell of a table in word document using c# ,it does not work ,why ? how to do it ?

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

as shown in the last line.

In the document, it is "sdsdlkfjdslk \r\n slkdfjslj", not "sdsdlkfjdslk slkdfjslj"

Upvotes: 1

Views: 8231

Answers (2)

jeffbricco
jeffbricco

Reputation: 134

(char)11 and \v did not work for me. I received "hexadecimal value 0x0B, is an invalid character". The following solution did the trick for me.

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

I ended up keeping the string, variable Value in the example, coming into the cell with "\n" as the line break. I split the string into an array on the line break. I only had a possibility of one break in my code but you could use a foreach to loop through if you have multiple line breaks.

Upvotes: 1

NibblyPig
NibblyPig

Reputation: 52952

Try

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

or

"sdsdlkfjdslk \v slkdfjslj"

Upvotes: 3

Related Questions