【发布时间】:2021-04-27 16:58:08
【问题描述】:
我正在尝试将富文本内容控件的内容从一个复制到另一个 Word 文档。每个富文本内容控件都包含一个文本块和一些纯文本内容控件。下面的代码似乎工作......
using (WordprocessingDocument doc = WordprocessingDocument.Open(destinationFile, true))
{
MainDocumentPart mainPart = doc.MainDocumentPart;
Dictionary<string, SdtBlock> sdtBlocks = getContentControlsFromDocument(sourceFile);
foreach (KeyValuePair<string, SdtBlock> sdtBlock in sdtBlocks)
{
SdtElement control = mainPart.Document.Body.Descendants<SdtElement>().Where(r =>
{
var tag = r.SdtProperties.GetFirstChild<Tag>();
return tag != null && tag.Val == sdtBlock.Key.ToLower();
}).FirstOrDefault();
SdtContentBlock cloneSdtContentBlock = (SdtContentBlock)sdtBlock.Value.Descendants<SdtContentBlock>().FirstOrDefault().Clone();
control.Parent.InsertAfter(cloneSdtContentBlock, control);
control.Remove();
}
mainPart.Document.Save();
}
但是当我尝试使用下面的代码在destinationFile 中查找所有内容控件时
string key = "tag_name";
List<SdtElement> controls = mainPart.Document.Body.Descendants<SdtElement>().Where(r =>
{
var tag = r.SdtProperties.GetFirstChild<Tag>();
return tag != null && tag.Val == key.ToLower();
}).ToList();
我找不到从sourceFile 复制的富文本内容控件中的内容。换句话说,我只想复制富文本内容控件的内容,而不复制控件本身。
更新:
为了简化问题。我有一个富文本内容控件,它可能有纯文本和几个纯文本内容控件。我只需要复制(仅)这个富文本内容控件中的内容,它将整个内容包装到另一个 Word 文档中。
【问题讨论】:
标签: c# ms-word openxml openxml-sdk