如何使用OpenXml将新书签附加到Word 2010中的现有段落?

时间:2016-06-27 06:29:28

标签: c# openxml word-2010

在word文档中,我想将书签设置为样式为"标题1和#34;的所有段落。

如何使用OpenXml将新书签插入现有段落?

1 个答案:

答案 0 :(得分:1)

要做到这一点,你必须:

  1. 查找所有段落
  2. 检查段落是否是带有Heading1的标题(您必须检查ParagraphProperties(...)内部是否存在paragraphStyleId()
  3. 如果它是带有Heading1样式的段落,请插入书签。
  4. 您应该可以使用像

    这样的代码执行此操作
            int bookmarkId = 0;
            // MyDocuments.Body is a WordProcessDocument.MainDocumentPart.Document.Body
            foreach(Paragraph para in MyDocuments.Body.Descendants<Paragraph>())
            {
                // if the paragraph has no properties or has properties but no pStyle, it's not a "Heading1"
                ParagraphProperties pPr = para.GetFirstChild<ParagraphProperties>();
                if (pPr == null || pPr.GetFirstChild<ParagraphStyleId>() == null) continue;
                // if the value of the pStyle is not Heading1 => skip the paragraph
                if (pPr.GetFirstChild<ParagraphStyleId>().Val != "Heading1") continue;
    
                // it's a paragraph with Heading1 style, insert the bookmark
    
                // the bookmark must have a start and an end
                // the bookmarkstart/end share the same id
                BookmarkStart bms = new BookmarkStart() { Name = "yourbookmarkname", Id = bookmarkId.ToString() };
                BookmarkEnd bme = new BookmarkEnd() { Id = bookmarkId.ToString() };
                ++bookmarkId;
    
                // Insertion of bookmarkstart after the paragraphProperties
                pPr.InsertAfterSelf(bms);
    
                // The bookmarkend can be inserted after the bookmarkstart or after the object the bookmark must surrounding
                // here we will insert it after bms. If you want to surround an object, find the object within the paragraph and insert it after
                bms.InsertAfterSelf(bme);
    

    有关书签类的更多信息,请访问:https://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.bookmarkstart(v=office.14).aspx