使用open xml添加文本后删除Content控件

时间:2015-03-13 23:16:02

标签: ms-word ms-office openxml docx openxml-sdk

在一些非常善良的社区成员的帮助下,我设法以编程方式创建一个函数,使用open xml替换Word文档中内容控件中的文本。生成文档后,我会在替换文本后删除文本的格式。

关于如何保持单词格式并删除内容控制标记的任何想法?

这是我的代码:

using (var wordDoc = WordprocessingDocument.Open(mem, true))
{

    var mainPart = wordDoc.MainDocumentPart;

    ReplaceTags(mainPart, "FirstName", _firstName);
    ReplaceTags(mainPart, "LastName", _lastName);
    ReplaceTags(mainPart, "WorkPhoe", _workPhone);
    ReplaceTags(mainPart, "JobTitle", _jobTitle);

    mainPart.Document.Save();
    SaveFile(mem);
}

private static void ReplaceTags(MainDocumentPart mainPart, string tagName,    string tagValue)
{
    //grab all the tag fields
    IEnumerable<SdtBlock> tagFields = mainPart.Document.Body.Descendants<SdtBlock>().Where
        (r => r.SdtProperties.GetFirstChild<Tag>().Val == tagName);

    foreach (var field in tagFields)
    {
        //remove all paragraphs from the content block
        field.SdtContentBlock.RemoveAllChildren<Paragraph>();
        //create a new paragraph containing a run and a text element
        Paragraph newParagraph = new Paragraph();
        Run newRun = new Run();
        Text newText = new Text(tagValue);
        newRun.Append(newText);
        newParagraph.Append(newRun);
        //add the new paragraph to the content block
        field.SdtContentBlock.Append(newParagraph);
    }
}

1 个答案:

答案 0 :(得分:1)

保持样式是一个棘手的问题,因为可能有多种样式应用于您要替换的文本。在那种情况下你应该怎么做?

假设一个样式的简单情况(但可能超过ParagraphsRunsTexts),您可以保留第一个Text您根据SdtBlock遇到的元素,并将所需的值放在该元素中,然后从Text中删除任何其他SdtBlock元素。然后将保留第一个Text元素的格式。显然,你可以将这个理论应用于任何Text块;你不必使用第一个。以下代码应显示我的意思:

private static void ReplaceTags(MainDocumentPart mainPart, string tagName, string tagValue)
{
    IEnumerable<SdtBlock> tagFields = mainPart.Document.Body.Descendants<SdtBlock>().Where
        (r => r.SdtProperties.GetFirstChild<Tag>().Val == tagName);

    foreach (var field in tagFields)
    {
        IEnumerable<Text> texts = field.SdtContentBlock.Descendants<Text>();

        for (int i = 0; i < texts.Count(); i++)
        {
            Text text = texts.ElementAt(i);

            if (i == 0)
            {
                text.Text = tagValue;
            }
            else
            {
                text.Remove();
            }
        }
    }
}