使用 C# 和 Office.Interop.Word 将文本替换为多行

Replace text with multilines using C# with Office.Interop.Word

希望您能找到这个问题。

我开发了一个名为 "CreateContract" 的应用程序,因为合同是一个 word 模板,这个应用程序的主要 objective 正在用通过 end 键入的输入替换一些存在于 word 模板中的特定文本windows 表单的用户。

如果我用一行文本替换文本,一切正常,通过使用 RichTextBox 控件将文本替换为多行文本时会出现问题。

我尝试了接下来的所有方法,但没有任何积极的结果:-

replaceWithText = replaceWithText.ToString().Replace(@"\n", @"\v"); 
replaceWithText = replaceWithText.ToString().Replace("\n", @"\v");
replaceWithText = replaceWithText.ToString().Replace(@"\n", @"\r");
replaceWithText = replaceWithText.ToString().Replace(@"\n", @"\r\n");
replaceWithText = replaceWithText.ToString().Replace(@"\n", "\u2028");

整个代码:-

static void FindAndReplace(Microsoft.Office.Interop.Word.Application fileOpen, object findText, object replaceWithText)
{
    //replaceWithText = replaceWithText.ToString().Replace(@"\n", @"\v");
    //replaceWithText = replaceWithText.ToString().Replace("\n", @"\v");
    //replaceWithText = replaceWithText.ToString().Replace("\n", @"\r");
    //replaceWithText = replaceWithText.ToString().Replace("\n", @"\r\n");
    //replaceWithText = replaceWithText.ToString().Replace(@"\n", "\u2028");


    object matchCase = false;
    object matchWholeWord = true;
    object matchWildCards = false;
    object matchSoundsLike = false;
    object matchAllWordForms = false;
    object forward = true;
    object format = false;
    object matchKashida = false;
    object matchDiacritics = false;
    object matchAlefHamza = false;
    object matchControl = false;
    object read_only = false;
    object visible = true;
    object replace = 2;
    object wrap = 1;

    //execute find and replace
    fileOpen.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
        ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace,
        ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);

}

问题是,在第一个代码块中,您使用的是 Verbatim 字符串文字。

您正在尝试用(例如)字符串“\r\n”替换文本“\n”。但实际上,您想用其他一些控制字符替换换行控制字符(0x0A – 通常转义为 \n)。当您使用 Verbatim String Literals 时,字符不会被转义。

对于您的预期结果,请从第一个代码块中的字符串开头删除那些 "at"(@) 符号。

-> replaceWithText = replaceWithText.ToString().Replace("\n", "\r\n"); 等等。