L3soft Studio

圆自己一个开发梦

2006年06月


C#编程实现在Excel文档中搜索文本
作者: it步行者   www.ASPCool.com 时间:2006-5-18 21:34:37  

     有了在Word文档中编程实现搜索文本的经验,在Excel中实现这个功能也并非难事。
  
    打开Excel的VBA帮助,查看Excel的对象模型,很容易找到完成这个功能需要的几个集合和对象:Application、Workbooks、Workbook、Worksheets还有Worksheet和Range。Application创建Excel应用,Workbooks打开Excel文档,Workbook获得Excel文档工作薄,Worksheets操作工作表集合,Worksheet获得单个工作表。
  
    搜索的思路对应上述集合和对象,可以这样表述:要搜索的文本可能存在Excel文档当中的某个工作表上,搜索应该遍历目标Excel文件的每个工作表中的有效区域,如果找到,则退出本次搜索,如果没有找到,则继续搜索直到完成本次搜索。
  
    跟Word对象模型不一样的是,Excel对象模型没有提供Find对象,不过没有关系,可以通过两种方法来实现,一个是通过Range对象的Find()方法来实现,另外一个比较麻烦,取得工作表Worksheet的有效区域UsedRange之后,遍历该Range对象中的所有行列。实际开发中,用第二种方法时发现了一个特别的现象,所以第二种方法也准备详细记述一下。
  
    第一步,打开Excel文档:
  
  
  
  object filename="";
  object MissingValue=Type.Missing;
  string strKeyWord=""; //指定要搜索的文本,如果有多个,则声明string[]
  Excel.Application ep=new Excel.ApplicationClass();
  Excel.Workbook ew=ep.Workbooks.Open(filename.ToString(),MissingValue,
   MissingValue,MissingValue,MissingValue,
   MissingValue,MissingValue,MissingValue,
   MissingValue,MissingValue,MissingValue,
   MissingValue,MissingValue,MissingValue,
   MissingValue);
  
    然后准备遍历Excel工作表:
  
  
  Excel.Worksheet ews;
  int iEWSCnt=ew.Worksheets.Count;
  int i=0,j=0;
  Excel.Range oRange;
  object oText=strKeyWord.Trim().ToUpper();
  
  for(i=1;i<=iEWSCnt;i++)
  {
   ews=null;
   ews=(Excel.Worksheet)ew.Worksheets[i];
   oRange=null;
   (Excel.Range)oRange=((Excel.Range)ews.UsedRange).Find(
   oText,MissingValue,MissingValue,
   MissingValue,MissingValue,Excel.XlSearchDirection.xlNext,
   MissingValue,MissingValue,MissingValue);
   if (oRange!=null && oRange.Cells.Rows.Count>=1 && oRange.Cells.Columns.Count>=1)
   {
   MessageBox.Show("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);
   break;
   }
  }
  
    这里要说两个值得注意的地方。一个是遍历工作表的索引,不是从0开始,而是从1开始;另外一个是Find方法的第六个参数SearchDirection,指定搜索的方向,帮助文档中说这个参数是可选项,但是我用MissingValue如论如何编译不能通过,不知什么原因,于是显式指定它的默认值xlNext。
  
    第一种方法实现了,再看看第二种方法。这种方法除了要遍历工作表,还要对工作表使用区域的行和列进行遍历。其它一样,只对遍历说明,代码如下:
  
  
  bool blFlag=false;
  int iRowCnt=0,iColCnt=0,iBgnRow,iBgnCol;
  
  for(m=1;m<=iEWSCnt;m++)
  {
   ews=(Excel.Worksheet)ew.Worksheets[m];
   iRowCnt=0+ews.UsedRange.Cells.Rows.Count;
   iColCnt=0+ews.UsedRange.Cells.Columns.Count;
   iBgnRow=(ews.UsedRange.Cells.Row>1)?
   ews.UsedRange.Cells.Row-1:ews.UsedRange.Cells.Row;
   iBgnCol=(ews.UsedRange.Cells.Column>1)?
   ews.UsedRange.Cells.Column-1:ews.UsedRange.Cells.Column;
  
   for(i=iBgnRow;i<iRowCnt+iBgnRow;i++)
   {
   for(j=iBgnCol;j<iColCnt+iBgnCol;j++)
   {
   strText=((Excel.Range)ews.UsedRange.Cells[i,j]).Text.ToString();
   if (strText.ToUpper().IndexOf(strKeyWord.ToUpper())>=0)
   {
   MessageBox.Show("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);
   }
   }
   }
  }
  
    显然这种方法比第一种繁琐得多,不过这里有一个关于遍历单元格的索引很特别的地方,当工作表中的使用区域UsedRange为单行单列的时候,对UsedRange中的单元格遍历起始索引值为1,为多行多列的时候,起始索引值为0,不知这是Excel程序设计者出于什么样的考虑?



用C#实现在Word文档中搜索文本
作者: it步行者   www.ASPCool.com 时间:2006-5-18 21:34:59  

     在word应用程序中搜索和替换文本是举手之劳的事情,通过word的对象模型,我们也可以使用编程方式来实现。
  
    Word的对象模型有比较详细的帮助文档,放在Office安装程序目录,office 2003是在Program Files\Microsoft Office\OFFICE11\2052下,文档本身是为VBA提供的,在这个目录下还可以看到所有的office应用程序的VBA帮助。
  
    打开VBAWD10.CHM,看到word的对象模型,根据以往的使用经验,很容易在Document对象下找到Content属性,该属性会返回一个文档文字部分的Range对象,从这个对象中不难取到所有的文档内容,再用string的IndexOf()方法很容易达到目标。
  
  object filename=""; //要打开的文档路径
  string strKey=""; //要搜索的文本
  object MissingValue=Type.Missing;
  
  Word.Application wp=new Word.ApplicationClass();
  Word.Document wd=wp.Documents.Open(ref filename,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue);
  
  if (wd.Content.Text.IndexOf(strKey)>=0)
  {
   MessageBox.Show("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);
  }
  else
  {
   MessageBox.Show("文档中没有指定的关键字!","搜索结果",MessageBoxButtons.OK);
  }
  
  
    不过,这种做法是很勉强的,对小文档来说,不存在问题,对超长超大的文档来说,这样的实现方法已经暗埋bug了,而且是程序级的bug,因为正常的测试会很难发现问题,在使用中导致程序出现什么样的结果也很难量化描述。
  
    其实,在word中已经提供了可以用作搜索的对象Find,在对象模型上也比较容易找到,对应的说明是这样的:该对象代表查找操作的执行条件。Find 对象的属性和方法与“替换”对话框中的选项一致。从模型上看,Find对象是Selection的成员,从示例代码来看似乎也是Range的成员,查找Range的属性,果然如此。于是修改上面的代码:
  
  
  
  wd.Content.Find.Text=strKey;
  if (wd.Content.Find.Execute(ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue))
  {
   MessageBox.Show("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);
  }
  else
  {
   MessageBox.Show("文档中没有指定的关键字!","搜索结果",MessageBoxButtons.OK);
  }
  
  
  
    这样似乎也不是最好,因为我只要判断指定的文本是不是在文档中,而不需要知道它出现了几次,如果有多个要搜索的文本,难道每次都进行全文档搜索?假设我要搜索的文本包含在文档中,最好的情况是在文档开头就包含我要查找的文本,最坏的情况是在文档的最后包含要查找的文本,如果每次取一部分文档进行判断,符合条件就结束本次搜索,就可以避免每次搜索整个文档了。模型中的Paragraphs对象现在派上用场了,再修改一下代码:
  
  
  int i=0,iCount=0;
  Word.Find wfnd;
  
  if (wd.Paragraphs!=null && wd.Paragraphs.Count>0)
  {
   iCount=wd.Paragraphs.Count;
   for(i=1;i<=iCount;i++)
   {
   wfnd=wd.Paragraphs[i].Range.Find;
   wfnd.ClearFormatting();
   wfnd.Text=strKey;
   if (wfnd.Execute(ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue,ref MissingValue,
   ref MissingValue))
   {
   MessageBox.Show("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);
   break;
   }
   }
  }



上一篇讲到,一个Document可能会有多个Rang对象。Rang由起始和结束字符来定他的位置。
以下代码为先清空Document里的内容,再在第一行写入内容。
    // Clear out any existing information.
    Object start = Type.Missing;
    Object end = Type.Missing;
     Object unit = Type.Missing;
    Object count = Type.Missing;
    ThisDocument.Range(ref start, ref end). Delete(ref unit, ref count);

    // Set up the header information.
    start = 0;
    end = 0;
     rng = ThisDocument.Range(ref start, ref end);
     rng.InsertBefore("Xiaopai");
     rng.Font.Name = "Verdana";
     rng.Font.Size = 16;
     rng.InsertParagraphAfter();//输入回车

以下为在刚写入的内容后添加一个表格。
    object missingValue = Type.Missing;
    object location = 8; //注:若location超过已有字符的长度将会出错。
    Word.Range rng = ThisDocument.Range(ref location, ref location);
    ThisDocument.Tables.Add(rng, 3, 4, ref missingValue, ref missingValue);

以下为在刚创建的表格里添加一行
    Word.Table tbl = ThisDocument.Tables[1]; //第一个表格为1,而不是0
    Object beforeRow = Type.Missing;
    tbl.Rows.Add(ref beforeRow); //在表格的最后添加一行

填充表格内容
    tbl.Cell(1, 1).Range.Text = "shuai"; //在表格的第一行第一列填入内容。

设置单元格风格
    Word.Range rngCell;
    rngCell = tbl.Cell(1, 2).Range;
    rngCell.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
    rngCell.Font.Size = 8;
    rngCell.Font.Name = "Verdana";

当时没找到合并单元格的方法。有谁知道的共享一下哈。

参考资料:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrtskhowtocreatewordtables.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrtskhowtoaddrowscolumnstowordtables.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odc_vsto2003_ta/html/odc_VSTWordtbl.asp




    摘要:
下图是Word对像模型


Application :用来表现WORD应用程序,包含其它所有对象。他的成员经常应用于整个WORD,你可以用它的属性和方法控制WORD环境。
Document :Document对象是WORD编程的核心。当你打开打开一个已有的文档或创建一个新的文档时,就创建了一个新的Documnet对象, 新创建的Document将会被添加到Word Documents Collection。
Selection :    (全文共9470字)——点击此处阅读全文


news

点击这里给我发消息

导航

blog stats

文章

收藏

相册

友情链接

存档


正在读取评论……