打印本文 关闭窗口 |
|
| C#编程实现在Excel文档中搜索文本 | |
| 作者:佚名 文章来源:不详 点击数 更新时间:2008/5/9 19:01:05 文章录入:杜斌 责任编辑:杜斌 | |
|
|
|
|
有了在Word文档中编程实现搜索文本的经验,在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程序设计者出于什么样的考虑? |
|
打印本文 关闭窗口 |