如何将标题应用于文字处理文档中的所有段落?

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

有没有办法遍历文档中的段落元素? 到目前为止,我也可以 select 个别段落应用 headers。但是我想遍历所有这些,或者 count() 我有多少,所以我可以使用 for 循环。

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);
}

你快到了。

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
        }
    }
}