[英]C# Word Document, replace selected Range text?
I was trying to do a find and replace in a word document, but because the text to find is over 255 characters, so it will run into error using the below method:我试图在 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);
I found someone have a solution which can manage to return the range which contains the long text in Word document, so I am trying to replace the text of this range and save the changes.我发现有人有一个解决方案,可以设法返回包含 Word 文档中长文本的范围,因此我尝试替换此范围的文本并保存更改。 But I couldn't figure out how to do the replacement after trying something like: Get the selected range containing long text
但是在尝试以下操作后,我无法弄清楚如何进行替换:获取包含长文本的选定范围
Microsoft.Office.Interop.Word.Range selectedRange = findTextRange(app, findText);
Try to replace the value of returned selectedRange with:尝试将返回的 selectedRange 的值替换为:
app.Selection.Range.Text = replaceWithText;
It doesn't have any problem to execute, but the saved document doesn't have the change.执行没有任何问题,但保存的文档没有更改。 So I am not sure what I missed?
所以我不确定我错过了什么? Thank you.
谢谢你。
Maybe findTextRange
doesn't select the range for you?也许
findTextRange
没有为您选择范围?
Microsoft.Office.Interop.Word.Range selectedRange = findTextRange(app, findText); app.Selection.Range.Text = replaceWithText;
Replace the 2nd line with:将第 2 行替换为:
selectedRange.Text = replaceWithText; // and, you might want to rename `selectedRange`
you can do using ASPOSE file formate API for this problem.This should be easy rather than another solution i think.Add this reference to your nuget of visual studio.您可以使用 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;
// We want the "your document" phrase to be highlighted. // 我们希望突出显示“您的文档”短语。
Regex regex = new Regex("your document", RegexOptions.IgnoreCase);
doc.Range.Replace(regex, "", options);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the output document. // 保存输出文档。
doc.Save(dataDir);
Please follow the below link: https://docs.aspose.com/display/wordsnet/Find+and+Replace请点击以下链接: https : //docs.aspose.com/display/wordsnet/Find+and+Replace
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.