45fan.com - 路饭网

搜索: 您的位置主页 > 电脑频道 > 编程代码 > 阅读资讯:如何通过asp.net操作Word实现批量替换?

如何通过asp.net操作Word实现批量替换?

2016-07-06 12:10:44 来源:www.45fan.com 【

如何通过asp.net操作Word实现批量替换?

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


本文地址:http://www.45fan.com/bcdm/56272.html
Tags: word 操作 ASP.NET
编辑:路饭网
推广内容
推荐阅读
热门推荐
推荐文章
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部