|
Using System;
Using System. Collections. Generic;
Using System. Diagnostics;
Using System. Linq;
Using System. Text;
Namespace TextReplace
{
Public class WordOperate: IDisposable
{
Private Microsoft. Office. Interop. Word. _ Application _ app;
Private Microsoft. Office. Interop. Word. _ Document _ doc;
Object _ nullobj = System. Reflection. Missing. Value;
/// <Summary>
/// Close the Word process
/// </Summary>
Public void KillWinword ()
{
Var p = Process. GetProcessesByName ("WINWORD ");
If (p. Any () p [0]. Kill ();
}
/// <Summary>
/// Open the word document
/// </Summary>
/// <Param name = "filePath"> </param>
Public void Open (string filePath)
{
_ App = new Microsoft. Office. Interop. Word. ApplicationClass ();
Object file = filePath;
_ Doc = _ app. Documents. Open (
Ref file, ref _ nullobj, ref _ nullobj,
Ref _ nullobj,
Ref _ nullobj,
Ref _ nullobj,
Ref _ nullobj, ref _ nullobj );
}
/// <Summary>
/// Replace the text in word
/// </Summary>
/// <Param name = "strOld"> Search text </param>
/// <Param name = "strNew"> replaced text </param>
Public void Replace (string strOld, string strNew)
{
_ App. Selection. Find. ClearFormatting ();
_ App. Selection. Find. Replacement. ClearFormatting ();
_ App. Selection. Find. Text = strOld;
_ App. Selection. Find. Replacement. Text = strNew;
Object objReplace = Microsoft. Office. Interop. Word. WdReplace. wdReplaceAll;
_ App. Selection. Find. Execute (ref _ nullobj,
Ref _ nullobj,
Ref _ nullobj,
Ref _ nullobj, ref objReplace, ref _ nullobj,
Ref _ nullobj, ref _ nullobj, ref _ nullobj );
}
/// <Summary>
/// Save
/// </Summary>
Public void Save ()
{
_ Doc. Save ();
}
/// <Summary>
/// Exit
/// </Summary>
Public void Dispose ()
{
_ Doc. Close (ref _ nullobj, ref _ nullobj, ref _ nullobj );
_ App. Quit (ref _ nullobj, ref _ nullobj, ref _ nullobj );
}
}
} |