百度首页 | 百度空间
 
查看文章
 
C#操作word,如何进行查找和替换?
2007-05-30 13:14

说明:请在工程中引用“Microsoft Word 9.0 object library”的Microsoft COM组件。该组件提供的类和方法来读取Word文档。

using System;
using System.IO;
using System.Reflection;
using Word;   

//----------------------------------------------------------------------


     string WordContent = "";
     object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
     Word.Application app = new ApplicationClass();
     try
     {
      object fileName = fileDoc.Value;

      object optional= Missing.Value;
      object visible=true;
      if(File.Exists(fileName.ToString()))
      {
       Word.Document doc = app.Documents.Open(
        ref fileName,
        ref optional,
        ref optional,
        ref optional,
        ref optional,
        ref optional,
        ref optional,
        ref optional,
        ref optional,
        ref optional,
        ref optional,
        ref visible);

       object first = 0;
       object units = WdUnits.wdCharacter;
       object last=doc.Characters.Count;
  
       Range    range= doc.Range(ref first, ref last);


       //替换
       #region 方法一,特点是非常简单
       //Word.range.Text = range.Text.Replace(txtOldValue.Text, txtNewValue.Text);
       #endregion

       #region 方法二,特别是可以实现复杂的查找替换
       Word.Find finder = range.Find;
       finder.ClearFormatting();
     
       object missingValue = Type.Missing;
       object findStr = txtOldValue.Text;
       object replaceStr = txtNewValue.Text;
       object replaceArea = Word.WdReplace.wdReplaceAll;

       if (finder.Execute(ref findStr, ref missingValue, ref missingValue,
        ref missingValue, ref missingValue, ref missingValue,
        ref missingValue, ref missingValue, ref missingValue,
        ref replaceStr, ref replaceArea, ref missingValue,
        ref missingValue, ref missingValue, ref missingValue))
       {
        //Text found,and replaceed
        //range.Select();
       }

       #endregion


       WordContent = "成功替换 " + txtOldValue.Text + " at " + DateTime.Now.ToString();
       saveChanges = WdSaveOptions.wdSaveChanges;
  
      }
      else
      {
       WordContent = "指定目录下的无该文件";
      }

      txtContent.Text = WordContent;
     
     }
     catch(Exception Ex)
     {
      txtContent.Text =     Ex.Message ;
     }
     finally
     {
      //退出保存
      object originalFormat = Missing.Value;
      object routeDocument = Missing.Value;
      app.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
      app = null;

     }


类别:程序人生 | 添加到搜藏 | 浏览() | 评论 (1)
 
网友评论:
1
2008-07-25 21:21
怎么实现记事本的查找替换呢?
 
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码:
 

     

©2008 Baidu