程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> asp.net操作Word實現批量替換

asp.net操作Word實現批量替換

編輯:ASP.NET基礎

首先引入Microsoft.Office.Interop.Word組件,該組件在安裝完office後在COM中出現。

代碼如下

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>
  /// 關閉Word進程
  /// </summary>
  public void KillWinword()
  {
   var p = Process.GetProcessesByName("WINWORD");
   if (p.Any()) p[0].Kill();
  }
  /// <summary>
  /// 打開word文檔
  /// </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>
  /// 替換word中的文字
  /// </summary>
  /// <param name="strOld">查找的文字</param>
  /// <param name="strNew">替換的文字</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>
  /// 保存
  /// </summary>
  public void Save()
  {
   _doc.Save();
  }
  /// <summary>
  /// 退出
  /// </summary>
  public void Dispose()
  {
   _doc.Close(ref _nullobj, ref _nullobj, ref _nullobj);
   _app.Quit(ref _nullobj, ref _nullobj, ref _nullobj);
  }
 }
}

以上就是關於asp.net如何操作Word實現批量替換的全部代碼,希望對大家的學習有所幫助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved