代码之家  ›  专栏  ›  技术社区  ›  Shell

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

  •  1
  • Shell  · 技术社区  · 12 年前

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

    enter image description here

    然后在更换 @C公司 parameter删除该参数的颜色和线条。

    在下面的屏幕截图中 20142015 是从中替换的值 @C公司 参数

    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');
    }
    

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

    提前感谢,任何帮助都将不胜感激。

    2 回复  |  直到 12 年前
        1
  •  3
  •   raj    12 年前

    尝试使用 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;
    }
    
        2
  •  1
  •   Shell    12 年前

    经过多次尝试,我终于找到了解决方案。但是,这并不意味着解决方案是由 拉杰 没有帮助。是的,它也能起作用。但不幸的是,我的文档设计非常复杂。所以每当我试图替换头部分的值时。文档删除了我给该参数(@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");
            }
        }
    }