【发布时间】:2017-11-07 13:28:02
【问题描述】:
我正在寻找替代方法来在 word 文档中搜索某些文本,然后将其替换为另一个文本。我目前使用 Find and Replace 方法工作,但是我想知道是否还有其他方法可以做到这一点。
我尝试的一种方法是逐段浏览并搜索文本,将其换出,然后将其粘贴到新的 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);
}
}
}
【问题讨论】:
-
您为什么要寻找内置方法的替代方法?
-
这是我正在写的一个程序。我只想知道我必须使用的不同选择。查找和替换内置方法有效,但不是我的最佳解决方案。