VS2013
不可內嵌
使用
object fileName = @"e:\xx.doc";
msWord opWord = new msWord(fileName);
opWord.Add("%1%");
opWord.Add("%2%");
opWord.Save();
object fileName = @"e:\xx.doc";
msWord opWord = new msWord(fileName);
opWord.Replace("%1%", "成功1");
opWord.Replace("%2%", "成功2");
opWord.Save();
程式
using System;
using System.Web;
public class msWord
{
private Microsoft.Office.Interop.Word.ApplicationClass WordApp;
private Microsoft.Office.Interop.Word.Document aDoc;
private object myFind;
private object missing = System.Reflection.Missing.Value;
public msWord(object fileName)
{
WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
// set the file name from the open file dialog
//object fileName = @"e:\xx.doc";//WordFileToRead.fi;
object readOnly = false;
object isVisible = true;
// Here is the way to handle parameters you don't care about in .NET
// Make word visible, so you can see what's happening
WordApp.Visible = true;
// Open the document that was chosen by the dialog
aDoc = WordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible);
// Activate the document so it shows up in front
aDoc.Activate();
myFind = WordApp.Selection.Find;
}
public void Save()
{
WordApp.Quit(Microsoft.Office.Interop.Word.WdSaveOptions.wdSaveChanges, Microsoft.Office.Interop.Word.WdOriginalFormat.wdOriginalDocumentFormat, false);
}
public void Add(string value)
{
WordApp.Selection.TypeText(value);
WordApp.Selection.TypeParagraph();
}
public void Replace( object old_findText, object new_replaceText )
{
object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
try
{
//string oMissing = "";
object[] Parameters;
Parameters = new object[15];
Parameters[0] = old_findText;
Parameters[1] = missing;
Parameters[2] = missing;
Parameters[3] = missing;
Parameters[4] = missing;
Parameters[5] = missing;
Parameters[6] = missing;
Parameters[7] = missing;
Parameters[8] = missing;
Parameters[9] = new_replaceText;
Parameters[10] = replaceAll;
Parameters[11] = missing;
Parameters[12] = missing;
Parameters[13] = missing;
Parameters[14] = missing;
//word.Selection.Find.Replacement.Font.Name = "黑体";
myFind.GetType().InvokeMember("Execute", System.Reflection.BindingFlags.InvokeMethod, null, myFind, Parameters);
}
catch (Exception ex)
{
}
}
}