开发者

Replacing bookmarks in docx file using OpenXml SDK and C++/CLI

I am trying to replace bookmark in docx with text in c++\cli using open xml SDK co开发者_StackOverflow社区ncept. The below piece of code will fetch bookmarks from word document and checks whether the bookmark matches the string “VERSION” if it is true, it is replaced with the string “0000” in the docx file.

Paragraph ^paragraph = gcnew Paragraph(); 
Run ^run = gcnew Run(); 
DocumentFormat::OpenXml::Wordprocessing::Text^ text = gcnew DocumentFormat::OpenXml::Wordprocessing::Text(“0000”);

run->AppendChild(text);
paragraph->AppendChild(run); 
IDictionary<String^, BookmarkStart^> ^bookmarkMap = 
            gcnew Dictionary<String^, BookmarkStart^>();

for each (BookmarkStart ^bookmarkStart in 
GlobalObjects::wordDoc->MainDocumentPart->RootElement->Descendants<BookmarkStart^>())
{
    if (bookmarkStart->Name->Value == “VERSION”) 
    {  
    bookmarkStart->Parent->InsertAt<Paragraph^>(paragraph,3);
    } 
}

The above code works fine in most scenarios(wherever we insert bookmarks), but sometimes times it fails and I am not able to find the reason. And if the bookmark is inserted at the starting position of a line, then after execution I am not able to open the docx file, there will be some errors. I tried giving the index value as 0 for InserAt method even this is not working.

Please provide a solution for the above.

Thanks in advance


See How to Retrieve the Text of a Bookmark from an OpenXML WordprocessingML Document for code that retrieves text. It is written in C#, but you could use the code directly from C++/CLI.

See Replacing Text of a Bookmark in an OpenXML WordprocessingML Document for an algorithm that you can use to replace text.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜