【问题标题】:Formatting removed when replacing text from word document header part从 word 文档标题部分替换文本时删除了格式
【发布时间】:2014-08-28 12:52:20
【问题描述】:

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

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

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

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

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文档标题中。

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

【问题讨论】:

  • 澄清一下 > 你的输出应该是EMPLOYMENT AGREEMENT | 20142015,对吧?
  • 是的。它应该显示与上面的屏幕截图相同。只是值应该被替换,格式不应该被删除。

标签: c# vb.net ms-word


【解决方案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;
}

【讨论】:

    【解决方案2】:

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

    我已经通过使用 Field(插入->快速部件->字段)来完成。现在,它工作正常。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 2012-07-23
      • 1970-01-01
      相关资源
      最近更新 更多