Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open XML: Word - Getting all Paragraphs marked as "Heading1" style

Using Word I have created a Docx with the standard normal.dot as a test. Hello-world level complexity.

I wish to get all the paragraphs which are styled with the "Heading1" style in Word.

I can get all the paragraphs, but don't know how to filter down to Heading1.

using (var doc = WordprocessingDocument.Open(documentFileName, false))
{
    paragraphs = doc.MainDocumentPart.Document.Body
                    .OfType<Paragraph>().ToList();
}
like image 727
Ian Vink Avatar asked Aug 13 '12 19:08

Ian Vink


1 Answers

    [Test]
    public void FindHeadingParagraphs()
    {

        var paragraphs = new List<Paragraph>();

        // Open the file read-only since we don't need to change it.
        using (var wordprocessingDocument = WordprocessingDocument.Open(documentFileName, false))
        {
            paragraphs = wordprocessingDocument.MainDocumentPart.Document.Body
                .OfType<Paragraph>()
                .Where(p => p.ParagraphProperties != null && 
                            p.ParagraphProperties.ParagraphStyleId != null && 
                            p.ParagraphProperties.ParagraphStyleId.Val.Value.Contains("Heading1")).ToList();
        }
    }
like image 191
Ian Vink Avatar answered Nov 07 '22 07:11

Ian Vink