替换OpenXML中的内容控件文本

时间:2015-07-31 15:46:48

标签: c# ms-word openxml word-contentcontrol

我有一个具有multy Rich Text Content Control的word文件我想更改它的文本。我使用此代码。

 using (WordprocessingDocument theDoc = WordprocessingDocument.Open(docName, true))
 {
    MainDocumentPart mainPart = theDoc.MainDocumentPart;
    foreach (SdtElement sdt in mainPart.Document.Descendants<SdtElement>())
    {
        SdtAlias alias = sdt.Descendants<SdtAlias>().FirstOrDefault();
        if (alias != null)
        {
            string sdtTitle = alias.Val.Value;
            var t = sdt.Descendants<Text>().FirstOrDefault();
            t.Text="Atul works at Microsoft as a .NET consultant. As a consultant his job is to design, develop and deploy";
        }
    }
 }

使用旧文本添加新文本。但我想replace这个!!!

1 个答案:

答案 0 :(得分:1)

您只需检索并更新sdtContent的第一个文本。 要替换所有这些,简单的方法是:

  • 删除所有文字
  • 添加新文字

使用以下代码更新您的代码:

if (alias != null)
{
    // delete all paragraph of the sdt
    sdt.Descendants<Paragraph>().ToList().ForEach(p => p.Remove());
    // insert your new text, who is composed of:
    // - A Paragraph
    // - A Run
    // - A Text
    sdt.Append(new Paragraph(new Run(new Text("As a consultant his job is to design, develop and love poney."))));
}

编辑:我忘记添加段落和运行

您可以在此处查看如何构建SdtContent https://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.sdtcontentblock(v=office.14).aspx