簡體   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