asp. net Operation Word for Batch Replacement

  • 2021-07-06 10:46:39
  • OfStack

First, the Microsoft. Office. Interop. Word component is introduced, which appears in COM after office is installed.

The code is as follows


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>
  ///  Shut down Word Process 
  /// </summary>
  public void KillWinword()
  {
   var p = Process.GetProcessesByName("WINWORD");
   if (p.Any()) p[0].Kill();
  }
  /// <summary>
  ///  Open 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, ref _nullobj,
     ref _nullobj, ref _nullobj, ref _nullobj,
     ref _nullobj, ref _nullobj, ref _nullobj, ref _nullobj);
  }

  /// <summary>
  ///  Replace word Words in 
  /// </summary>
  /// <param name="strOld"> Find text </param>
  /// <param name="strNew"> Alternative 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 _nullobj, ref _nullobj,
          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>
  ///  Quit 
  /// </summary>
  public void Dispose()
  {
   _doc.Close(ref _nullobj, ref _nullobj, ref _nullobj);
   _app.Quit(ref _nullobj, ref _nullobj, ref _nullobj);
  }
 }
}

The above is about asp. net how to operate Word to achieve batch replacement of all the code, I hope to help you learn.


Related articles: