
替换指定Document的内容,并保存到指定的路径
#region 替换指定Document的内容,并保存到指定的路径
/// <summary>
/// 替换指定Document的内容,并保存到指定的路径
/// </summary>
/// <param name="docObject">Document</param>
/// <param name="savePath">保存到指定的路径</param>
protected void ReplaceWordDocAndSave(Document docObject,
object savePath)

{
object format = WdSaveFormat.wdFormatDocument;
object readOnly =
false;
object isVisible =
false;
string strOldText =
"{WORD}";
string strNewText =
"{替换后的文本}";

List<
string> IListOldStr =
new List<
string>();

IListOldStr.Add(
"{WORD1}");

IListOldStr.Add(
"{WORD2}");

Object Nothing = System.Reflection.Missing.Value;

Microsoft.Office.Interop.Word.Application wordApp =
new ApplicationClass();
//Microsoft.Office.Interop.Word.Document oDoc = wordApp.Documents.Open(ref obj, ref Nothing, ref readOnly, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref isVisible, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

Microsoft.Office.Interop.Word.Document oDoc = docObject;
object FindText, ReplaceWith, Replace;
object MissingValue = Type.Missing;
foreach (
string str
in IListOldStr)

{

oDoc.Content.Find.Text = str;
//要查找的文本

FindText = str;
//替换文本

ReplaceWith = strNewText;
//wdReplaceAll - 替换找到的所有项。
//wdReplaceNone - 不替换找到的任何项。
//wdReplaceOne - 替换找到的第一项。

Replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
//移除Find的搜索文本和段落格式设置

oDoc.Content.Find.ClearFormatting();
if (oDoc.Content.Find.Execute(
ref FindText,
ref MissingValue,
ref MissingValue,
ref MissingValue,
ref MissingValue,
ref MissingValue,
ref MissingValue,
ref MissingValue,
ref MissingValue,
ref ReplaceWith,
ref Replace,
ref MissingValue,
ref MissingValue,
ref MissingValue,
ref MissingValue))

{

Response.Write(
"替换成功!");

Response.Write(
"<br>");

}
else

{

Response.Write(
"没有相关要替换的:(" + str +
")字符");

Response.Write(
"<br>");

}

}

oDoc.SaveAs(
ref savePath,
ref Nothing,
ref Nothing,
ref Nothing,
ref Nothing,
ref Nothing,
ref Nothing,
ref Nothing,
ref Nothing,
ref Nothing,
ref Nothing,
ref Nothing,
ref Nothing,
ref Nothing,
ref Nothing,
ref Nothing);
//关闭wordDoc文档对象

oDoc.Close(
ref Nothing,
ref Nothing,
ref Nothing);
//关闭wordApp组件对象

wordApp.Quit(
ref Nothing,
ref Nothing,
ref Nothing);

}

#endregion