Albert Gil
Albert Gil

Reputation: 149

How can i apply headings to all paragraphs in a word processing document?

Is there a way to loop through the paragraph elements inside a document? So far i can select individual paragraphs to apply headers too. But i want to either loop through all of them, or count() how many i have so i can use a for loop.

using (WordprocessingDocument doc = WordprocessingDocument.Open(fileName, true))
{
    int i = 0;
    Paragraph p = doc.MainDocumentPart.Document.Body.Descendants<Paragraph>().ElementAt(i);

    // Check for a null reference. 
    if (p == null)
    {
        throw new ArgumentOutOfRangeException("p", "Paragraph was not found.");
    }
    ApplyStyleToParagraph(doc, "Heading1", "Heading 1", p);
}

Upvotes: 0

Views: 263

Answers (1)

Sach
Sach

Reputation: 10393

You're almost there.

using (WordprocessingDocument doc = WordprocessingDocument.Open(fileName, true))
{
    var paragraphs = doc.MainDocumentPart.Document.Body.Descendants<Paragraph>().ToList();

    foreach (var para in paragraphs)
    {
        if (para == null)
        {
            // Throw exception
        }
        else
        {
            // Apply style
        }
    }
}

Upvotes: 2

Related Questions