我正在尝试使用开放 xml SDK 概念将 docx 中的书签替换为 c++\cli 中的文本。
下面的代码将从Word文档中获取书签,并检查书签是否与字符串“VERSION”匹配,如果匹配,则将其替换为docx文件中的字符串“0000”。
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文件,会出现一些错误。
我尝试将 InserAt 方法的索引值设置为 0,即使这不起作用。
请针对以上问题提供解决方案。
提前致谢
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)
请参阅如何从 OpenXML WordprocessingML 文档中检索书签的文本,获取检索文本的代码。它是用 C# 编写的,但您可以直接使用 C++/CLI 中的代码。
请参阅替换 OpenXML WordprocessingML 文档中的书签文本,了解可用于替换文本的算法。
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.