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

孤街浪徒 提交于 2019-12-11 07:58:44

问题


I am trying to replace bookmark in docx with text in c++\cli using open xml SDK concept. 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


回答1:


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.



来源:https://stackoverflow.com/questions/7026449/replacing-bookmarks-in-docx-file-using-openxml-sdk-and-c-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!