欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net操作Word实现批量替换

程序员文章站 2023-12-19 13:37:46
首先引入microsoft.office.interop.word组件,该组件在安装完office后在com中出现。 代码如下 using system;...

首先引入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实现批量替换的全部代码,希望对大家的学习有所帮助。

上一篇:

下一篇: