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



有没有办法循环访问文档中的段落元素? 到目前为止,我也可以选择单个段落来应用标题。但是我想要么遍历所有这些,要么计算((我有多少,这样我就可以使用 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
}
}
}

最新更新