从word文档标题部分替换文本时删除格式

时间:2014-07-26 05:00:33

标签: c# vb.net ms-word

我正在创建一个应用程序,它接受文档并用给定的值替换一些参数。问题是当我用任何文本替换参数值@CCompany时,格式化被删除。实际文件看起来像这样。

enter image description here

然后在替换@CCompany参数后,该参数的颜色和行将被删除。

在以下屏幕截图中,20142015是已从@CCompany参数替换的值。

enter image description here

替换我正在使用的文档标题文本的代码在这里。

foreach (Word.Section section in myDocUpdate.Sections)
{
    Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
    headerRange.Text = headerRange.Text.Replace("@CCompany", '20142015');
}

我的要求是当我用指定的值替换参数时,不应删除格式。我该怎么办?还有其他办法吗?例如,使用fieldtextarea。但是,必须在Word文档标题中写入标题文本。

在此先感谢,任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

尝试使用ParagraphFormat.Duplicate制作当前格式的副本,并在更改文本后将其还原。 Here就是一个例子。

foreach (Word.Section section in myDocUpdate.Sections)
{
    Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
var oldHeaderFormat = headerRange.ParagraphFormat.Duplicate;
    headerRange.Text.Replace("@CCompany", '20142015');
    headerRange.ParagraphFormat = oldHeaderFormat;
}

答案 1 :(得分:1)

经过lof尝试后我终于得到了解决方案。但是,并不意味着 raj 给出的解决方案没有帮助。是的,它也可以工作。但是,遗憾的是我的文档设计非常复杂。所以每当我尝试替换标题部分的值时。该文档删除了我给该参数的格式(@CCompany)。

我是通过使用字段(插入 - >快速部分 - >字段)完成的。现在,它运作正常。

Microsoft.Office.Interop.Word.HeadersFooters headers = section.Headers;
foreach (Microsoft.Office.Interop.Word.HeaderFooter header in headers)
{
    Word.Fields fields = header.Range.Fields;
    foreach (Word.Field field in fields)
    {
        //I can check also the field text which i want to replace 
        //if there are multiple fields created with different value
        if (field.Type == Microsoft.Office.Interop.Word.WdFieldType.wdFieldUserName)
        {
            field.Select();
            field.Delete();
            wordApp.Selection.TypeText("Company Name");
        }
    }
}