繁体   English   中英

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

[英]C# Word Document, replace selected Range text?

我试图在 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;

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

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

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

将第 2 行替换为:

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

您可以使用 ASPOSE 文件格式 API 来解决此问题。这应该很容易,而不是我认为的另一种解决方案。将此参考添加到您的 Visual Studio nuget。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM