Problem editing Word doc, losing formatting RRS feed

  • Question

  • Hello all,

    I'm trying to trim leading and trailing carriage returns that may have been added when building my Word doc using following code:

    for (int i = 1; i <= doc.Sections.Count; i++)
       doc.Sections[i].Range.Text = doc.Sections[i].Range.Text.Trim();   //also tried Trim(new char[] {'\r'})

    But this also trims out the "\a" escape sequences which I believe are there to indicate tables, so my formatting is completely messed up after this trim.  Also, even if I don't trim and just use:

    doc.Sections[i].Range.Text = doc.Sections[i].Range.Text;

    I still lose the formatting.

    Any ideas on how to edit without losing formatting?

    Wednesday, August 1, 2012 2:26 PM


  • I see your problem. Cell boundaries are represented in the text using Unicode 13, the same as a carriage return....

    You've found the Trim method works for your task most of the time, so I'd stick with that. I would try iterating over the paragraphs in the document, testing to see whether they're part of a table, and if not then trimming them. Each table cell, in my experience, is taken as a separate paragraph.

    So something along the lines of:

    foreach (Word.Paragraph p in doc.Content)
      if (p.Range.get_Information(Word.WdInformation.wdWithInTable) == false)
           p.Range.Text = p.Range.Text.Trim(); 
    Wednesday, August 1, 2012 6:39 PM