Search code examples
c#ms-wordoffice-interop

Edit Text size/font using c# Interop for text just added using "oDoc.Content.Text += reportText.Heading"


        foreach (ReportItem reportItem in reportItems)
        {
            if (reportItem is ReportText reportText)
            {
                oDoc.Content.Text += reportText.Heading;
                oDoc.Content.Text += reportText.Text;
            }

        }
        oDoc.Save();
        oDoc.Close();
        word.Quit();

Each reportItem has text and a header. I want the header to be larger than the text and maybe bold. However i dont know how to select that text that has just been entered. Ive tried to select paragraphs but that seems to be erratic and i cant seem to get it right.


Solution

  • Rather than trying to assign to the entire docuemnt's content, use Range objects as the data "targets". Each section of text that should be formatted differently needs to be inserted individually (so you can't use += for all the content).

    Based on the example in the question, that could look something like this:

    Word.Range rngTarget = oDoc.Content;
    object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
        foreach (ReportItem reportItem in reportItems)
        {
            if (reportItem is ReportText reportText)
            {
                rngTarget.Text = reportText.Heading;
                rngTarget.Font.Size = 12;
                rngTarget.Bold = -1;
                rngTarget.Collapse(ref oCollapseEnd);
                rngTarget.Text += reportText.Text;
                rngTarget.Font.Size = 10;
                rngTarget.Bold = 0;
                rngTarget.Collapse(ref oCollapseEnd);
            }
        }
        oDoc.Save();
        oDoc.Close();
        word.Quit();
    

    If you absolutely feel you must use += then you need to include "markers" in the text to indicate the start and end points of "Header" and "Text". After the content has been inserted you'd then need to use Word's Find functionality to locate these and apply the formatting.