我正在寻找其他搜索并替换文档中特定文本的方法。目前我的方法是使用“查找和替换”功能,但我想知道是否有其他方法。
我尝试过的一种方法是逐段查找文本,将其替换并粘贴到一个新的Word文档中保存。但是,当涉及到图像、教科书、表格等内容时,这会使事情变得更加复杂。此外,格式也无法得到保留,这是另一个问题。
我的当前代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
namespace Test
{
static class Program
{
static void Main()
{
//Create a new microsoft word file
Microsoft.Office.Interop.Word.Application fileOpen = new Microsoft.Office.Interop.Word.Application();
//Open a already existing word file into the new document created
Microsoft.Office.Interop.Word.Document document = fileOpen.Documents.Open(@"C:\Users\dpatel\Desktop\Test1.docx", ReadOnly: false);
//Make the file visible
fileOpen.Visible = true;
document.Activate();
//The FindAndReplace takes the text to find under any formatting and replaces it with the
//new text with the same exact formmating (e.g red bold text will be replaced with red bold text)
FindAndReplace(fileOpen, "useless", "very useful");
//Save the editted file in a specified location
//Can use SaveAs instead of SaveAs2 and just give it a name to have it saved by default
//to the documents folder
document.SaveAs2(@"C:\Users\dpatel\Desktop\NewFile1");
//Close the file out
fileOpen.Quit();
}
//Method to find and replace the text in the word document. Replaces all instances of it
static void FindAndReplace(Microsoft.Office.Interop.Word.Application fileOpen, object findText, object replaceWithText)
{
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);
}
}
}