0

I am writing an application in C# that uses the Microsoft Office interop DLL to read a Word document. This is working fine.

I'd now like to also determine the formatting applied to the words I'm reading--for example, check if it's bold or italic or underlined. How can I do this?

reuben
  • 3,280
  • 21
  • 28
kabir
  • 532
  • 3
  • 9
  • 27

1 Answers1

0

You should use the Bold, Italic or Underline properties of the Microsoft.Office.Interop.Word.Range object.

This is an example of code:

  Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
        string fileName = @"C:\folder\document.docx";
        Document wordDoc = wordApp.Documents.Open(fileName);
        Microsoft.Office.Interop.Word.Range rng = wordDoc.Range();
        foreach (Microsoft.Office.Interop.Word.Range word in rng.Words)
        {
            if (word.Bold == -1)
            {
                //Do wathever you want with the bold text                    
            }
            else if (word.Italic == -1)
            {
                //Do wathever you want with the italic text
            }
            else if ( ((WdUnderline) word.Underline) == WdUnderline.wdUnderlineSingle)
            {
                //Do wathever you want with the underline text
            }
        }

        wordApp.Documents.Close();
        wordApp.Quit();

Note that the properties word.Bold and word.Italic don't return TRUE or FALSE, but an integer that represents one of three possible states. From MSDN:

This property returns True, False or wdUndefined (a mixture of True and False).

The value -1 corresponds to TRUE in these cases. Otherwise the word.Underline property is an enumeration and you can find all the possible values here: WdUnderline enumeration

Sara
  • 101
  • 6