使用OpenXml SDK和C ++ / CLI替换docx文件中的书签 [英] Replacing bookmarks in docx file using OpenXml SDK and C++/CLI

查看:757
本文介绍了使用OpenXml SDK和C ++ / CLI替换docx文件中的书签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用open xml SDK的概念,用c ++ \cli中的文本替换docx中的书签。
下面的代码将从word文档获取书签,并检查书签是否匹配字符串VERSION,如果它是真的,它将替换为docx文件中的字符串0000。

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

上述代码在大多数场景插入书签),但有时候它失败,我不能找到原因。
如果书签插入在一行的开始位置,那么在执行后我无法打开docx文件,会有一些错误。
我试图给索引值为0的InserAt方法,即使这是不工作。

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.

请提供上述解决方案。

提前感谢

推荐答案

请参阅如何从检索文本的代码中获取书签的文本。它是用C#编写的,但您可以直接使用C ++ / CLI中的代码。

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.

请参阅在OpenXML WordprocessingML文档中替换书签的文本用于可用于替换文本的算法。

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

这篇关于使用OpenXml SDK和C ++ / CLI替换docx文件中的书签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆