user1523566
user1523566

Reputation: 37

How to get a paragraphs number in a word document with C#?

I use the assembly Microsoft.Office.Interop.Word;

My document is a Microsoft.Office.Interop.Word.Document object, and I want to get the number of each paragraph in this document.

How can I do this?

Upvotes: 3

Views: 9579

Answers (3)

Francesco Baruchelli
Francesco Baruchelli

Reputation: 7468

You need something like this:

    object misValue = System.Reflection.Missing.Value;
    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
    object docPth = @"c:\tmp\aDoc.doc";
    Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(ref docPth, ref misValue, ref misValue,
        ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue,
        ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue);
    wordApp.Visible = true;
    foreach (Microsoft.Office.Interop.Word.Paragraph aPar in aDoc.Paragraphs)
    {
        Microsoft.Office.Interop.Word.Range parRng = aPar.Range;
        string sText = parRng.Text;
        string sList = parRng.ListFormat.ListString;
        int nLevel = parRng.ListFormat.ListLevelNumber;
        MessageBox.Show("Text = " + sText + " - List = " + sList + " - Level " + nLevel.ToString());
    }

Upvotes: 5

JohnZaj
JohnZaj

Reputation: 3230

If you have a Document object, you can already get the 'number' or 'index' of each Paragraph in the document. For example, if you need to get the Text of the second paragraph in the document, you say:

MSWord.Application app = (MSWord.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
MSWord.Document doc = app.ActiveDocument; //the document that's on screen and 'active'

Console.WriteLine("Paragraph Count: " + doc.Paragraphs.Count); //show total number of paragraphs available in document.
Console.Write Line("Paragraph number 2 text: " + doc.Paragraphs[2].Range.Text);               //show text of paragraph number 2

Console.ReadLine();

If this doesn't help. PLEASE...edit your question. We really cannot do anything with this until you clarify.

Upvotes: 0

Snake Eyes
Snake Eyes

Reputation: 16764

Before start using Microsoft.Office.Interop.Word library/dll, you must read documentation of that library.

Read here:

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.paragraphs_members.aspx

Also, depends what version of Office do you use.

Upvotes: 1

Related Questions