说明:请在工程中引用“Microsoft Word 9.0 object library”的Microsoft COM组件。该组件提供的类和方法来读取Word文档。
using System;
using System.IO;
using System.Reflection;
using Word;
//----------------------------------------------------------------------
string WordContent = "";
object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
Word.Application app = new ApplicationClass();
try
{
object fileName = fileDoc.Value;
object optional= Missing.Value;
object visible=true;
if(File.Exists(fileName.ToString()))
{
Word.Document doc = app.Documents.Open(
ref fileName,
ref optional,
ref optional,
ref optional,
ref optional,
ref optional,
ref optional,
ref optional,
ref optional,
ref optional,
ref optional,
ref visible);
object first = 0;
object units = WdUnits.wdCharacter;
object last=doc.Characters.Count;
Range range= doc.Range(ref first, ref last);
//替换
#region 方法一,特点是非常简单
//Word.range.Text = range.Text.Replace(txtOldValue.Text, txtNewValue.Text);
#endregion
#region 方法二,特别是可以实现复杂的查找替换
Word.Find finder = range.Find;
finder.ClearFormatting();
object missingValue = Type.Missing;
object findStr = txtOldValue.Text;
object replaceStr = txtNewValue.Text;
object replaceArea = Word.WdReplace.wdReplaceAll;
if (finder.Execute(ref findStr, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue,
ref replaceStr, ref replaceArea, ref missingValue,
ref missingValue, ref missingValue, ref missingValue))
{
//Text found,and replaceed
//range.Select();
}
#endregion
WordContent = "成功替换 " + txtOldValue.Text + " at " + DateTime.Now.ToString();
saveChanges = WdSaveOptions.wdSaveChanges;
}
else
{
WordContent = "指定目录下的无该文件";
}
txtContent.Text = WordContent;
}
catch(Exception Ex)
{
txtContent.Text = Ex.Message ;
}
finally
{
//退出保存
object originalFormat = Missing.Value;
object routeDocument = Missing.Value;
app.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
app = null;
}