Search code examples
c#ms-wordoffice-interopword-interop

How to reverse paragraphs with Interop.Word


I am trying to reverse document paragraphs with the following code:

using Word = Microsoft.Office.Interop.Word;

object filePath = @"input.docx";
Word.Application app = new();
app.Visible = false;
object missing = System.Type.Missing;
object readOnly = false;
object isVisible = false;
Word.Document doc = app.Documents.Open(
    ref filePath,
    ref missing, ref readOnly, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref isVisible, ref missing,
    ref missing, ref missing, ref missing);
try
{
    Word.Range cachedPara2 = doc.Paragraphs[2].Range.Duplicate;
    doc.Paragraphs[2].Range.FormattedText = doc.Paragraphs[1].Range.FormattedText;
    doc.Paragraphs[1].Range.FormattedText = cachedPara2.FormattedText;
    doc.SaveAs(@"output.docx");
}
finally
{
    doc.Close();
    app.Quit();
}

I expect this:

enter image description here

but the actual result is this:

enter image description here

How to get expectations?


UPDATE

With the answer below, I was able to get the expected result for my first case.

Now, in another case, I wanna do the following:

enter image description here

Unfortunately, I couldn't quite figure it out how .Collabse() method works. I am trying to do it with .InsertParagraphAfter():

doc.Paragraphs[2].Range.InsertParagraphAfter();
doc.Paragraphs[3].Range.FormattedText = doc.Paragraphs[5].Range.FormattedText;
doc.Paragraphs[5].Range.FormattedText = doc.Paragraphs[2].Range.FormattedText;
doc.Paragraphs[2].Range.Delete();

enter image description here

Where does this empty paragraph come from? How avoid it?


Solution

  • A range object does not have any content itself, it merely points to the location of the content, rather like a set of map co-ordinates.

    What you need to do is add the content of the second paragraph before the first, which will create a new first paragraph. You can then delete what is now the third paragraph. For example:

    Word.Range target = doc.Paragraphs[1].Range;
    target.Collapse wdCollapseStart;
    target.FormattedText = doc.Paragraphs[2].Range.FormattedText;
    doc.Paragraphs[3].Range.Delete;