C#Word文档,替换选定的范围文本?

时间:2017-09-27 19:22:21

标签: c# ms-word

我试图在word文档中进行查找和替换,但因为要查找的文本超过255个字符,所以使用以下方法会遇到错误:

app.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);

我发现有人有一个解决方案可以设法返回包含Word文档中长文本的范围,因此我尝试替换此范围的文本并保存更改。但在尝试以下方法后,我无法弄清楚如何进行更换: 获取包含长文本的选定范围

Microsoft.Office.Interop.Word.Range selectedRange = findTextRange(app, findText);

尝试将返回的selectedRange的值替换为:

app.Selection.Range.Text = replaceWithText;

执行没有任何问题,但保存的文档没有更改。所以我不确定我错过了什么? 谢谢。

2 个答案:

答案 0 :(得分:0)

也许findTextRange没有为您选择范围?

Microsoft.Office.Interop.Word.Range selectedRange = findTextRange(app, findText);
app.Selection.Range.Text = replaceWithText;

将第二行替换为:

selectedRange.Text = replaceWithText; // and, you might want to rename `selectedRange`

答案 1 :(得分:0)

你可以使用ASPOSE文件格式化API来解决这个问题。这应该很容易,而不是我认为的另一种解决方案。将这个参考添加到你的视觉工作室中。

string dataDir = RunExamples.GetDataDir_FindAndReplace();
string fileName = "TestFile.doc";

Document doc = new Document(dataDir + fileName);

FindReplaceOptions options = new FindReplaceOptions();
options.ReplacingCallback = new ReplaceEvaluatorFindAndHighlight();
options.Direction = FindReplaceDirection.Backward;

//我们希望突出显示“您的文档”短语。

Regex regex = new Regex("your document", RegexOptions.IgnoreCase);
doc.Range.Replace(regex, "", options);

dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);

//保存输出文档。

doc.Save(dataDir);

请点击以下链接: https://docs.aspose.com/display/wordsnet/Find+and+Replace