替换OpenXML中内容控件的文本 [英] Replacing Text of Content Controls in OpenXML

查看:133
本文介绍了替换OpenXML中内容控件的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个Rich Text Content Control的Word文件,我想更改其文本.我使用此代码.

I have a word file that have multy Rich Text Content Control I want to change text of it. I Use this code .

 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这个!

It is add new text with old text. But i want to replace this!!!

推荐答案

您只能检索和更新sdtContent的第一个Text. 要替换所有这些,简单的方法是:

You only retrieve and update the first Text of your sdtContent. To replace all of it, the simples way is:

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

使用以下代码更新代码:

Update your code with:

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

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

edit: I forget to add the paragraph and the run

您可以在此处 https://msdn.microsoft.com/zh-cn/library/documentformat.openxml.wordprocessing.sdtcontentblock(v = office.14).aspx

这篇关于替换OpenXML中内容控件的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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