打开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对象中的所有行列。实际开发中,用第二 种方法时发现了一个特别的现象,所以第二种方法也准备详细记述一下。   

1. 打开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);

2. 准备遍历Excel工作表

2.1 方法1

  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。

2.2 方法2
第一种方法实现了,再看看第二种方法。这种方法除了要遍历工作表,还要对工作表使用区域的行和列进行遍历。其它一样,只对遍历说明,代码如下:

  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{for(j=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程序设计者出于什么样的考虑?

2.3 方法二补充案例

有效数据的行列数,可以通过下面的代码获取。

 nUsedRow = sheet.UsedRange.Rows.Count;
 nUsedCol =  sheet.UsedRange.Columns.Count;

本文表示对参考文章1,文章2.2中原作者所说的那种奇怪的现象表示质疑,并不会出现那种情况。 2016-8-27

准备工作

private void createOutputFile(string excelFullFilename){bool isAutoFit = true;bool isHeaderBold = true;Excel.Application xlApp = new Excel.Application();Excel.Workbook xlWorkBook;Excel.Worksheet xlWorkSheet;object misValue = System.Reflection.Missing.Value;xlApp = new Excel.ApplicationClass();xlWorkBook = xlApp.Workbooks.Add(misValue);xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);const int excelRowHeader = 1;const int excelColumnHeader = 1;//save headerint curColumnIdx = 0 + excelColumnHeader;int rowIdx = 0 + excelRowHeader;xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "Title";xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "Description";const int constBullerLen = 5;for (int bulletIdx = 0; bulletIdx < constBullerLen; bulletIdx++){int bulletNum = bulletIdx + 1;xlWorkSheet.Cells[rowIdx, curColumnIdx + bulletIdx] = "Bullet" + bulletNum.ToString();}curColumnIdx = curColumnIdx + constBullerLen;const int constImgNameListLen = 5;for (int imgIdx = 0; imgIdx < constImgNameListLen; imgIdx++){int imgNum = imgIdx + 1;xlWorkSheet.Cells[rowIdx, curColumnIdx + imgIdx] = "ImageFilename" + imgNum.ToString();}curColumnIdx = curColumnIdx + constImgNameListLen;xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "HighestPrice";xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "OneSellerIsAmazon";xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "ReviewNumber";xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "IsBestSeller";//formatting//(1) header to boldif (isHeaderBold){Range headerRow = xlWorkSheet.get_Range("1:1", System.Type.Missing);headerRow.Font.Bold = true;}//(2) auto adjust column width (according to content)if (isAutoFit){Range allColumn = xlWorkSheet.Columns;allColumn.AutoFit();}//output
            xlWorkBook.SaveAs(excelFullFilename,XlFileFormat.xlWorkbookNormal,misValue,misValue,misValue,misValue,XlSaveAsAccessMode.xlExclusive,XlSaveConflictResolution.xlLocalSessionChanges,misValue,misValue,misValue,misValue);xlWorkBook.Close(true, misValue, misValue);xlApp.Quit();crl.releaseObject(xlWorkSheet);crl.releaseObject(xlWorkBook);crl.releaseObject(xlApp);}

View Code

现在需要用C#去打开已经存在的一个excel,并且找到最后一行,然后按行,继续添加内容。

private void appendInfoToFile(string fullFilename, AmazonProductInfo productInfo){Excel.Application xlApp;Excel.Workbook xlWorkBook;Excel.Worksheet xlWorkSheet;object missingVal = System.Reflection.Missing.Value;xlApp = new Microsoft.Office.Interop.Excel.Application();//xlApp.Visible = true;//xlApp.DisplayAlerts = false;//http://msdn.microsoft.com/zh-cn/library/microsoft.office.interop.excel.workbooks.open%28v=office.11%29.aspxxlWorkBook = xlApp.Workbooks.Open(Filename : fullFilename,//UpdateLinks:3,ReadOnly : false,//Format : 2, //use Commas as delimiter when open text file//Password : missingVal,//WriteResPassword : missingVal,//IgnoreReadOnlyRecommended: false, //when save to readonly, will notice youOrigin: Excel.XlPlatform.xlWindows, //xlMacintosh/xlWindows/xlMSDOS//Delimiter: ",",  // usefule when is text fileEditable : true,Notify : false,//Converter: missingVal, AddToMru: true, //True to add this workbook to the list of recently used filesLocal: true,CorruptLoad: missingVal //xlNormalLoad/xlRepairFile/xlExtractData
                );//Get the first sheetxlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); //also can get by sheet nameExcel.Range range = xlWorkSheet.UsedRange;//int usedColCount = range.Columns.Count;int usedRowCount = range.Rows.Count;const int excelRowHeader = 1;const int excelColumnHeader = 1;//int curColumnIdx = usedColCount + excelColumnHeader;int curColumnIdx = 0 + excelColumnHeader; //start from column beginint curRrowIdx = usedRowCount + excelRowHeader; // !!! here must added buildin excelRowHeader=1, otherwise will overwrite previous (added title or whole row value)
xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.title;xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.description;const int constBullerLen = 5;int bulletListLen = 0;if (productInfo.bulletArr.Length > constBullerLen){bulletListLen = constBullerLen;}else{bulletListLen = productInfo.bulletArr.Length;}for (int bulletIdx = 0; bulletIdx < bulletListLen; bulletIdx++){xlWorkSheet.Cells[curRrowIdx, curColumnIdx + bulletIdx] = productInfo.bulletArr[bulletIdx];}curColumnIdx = curColumnIdx + bulletListLen;const int constImgNameListLen = 5;int imgNameListLen = 0;if (productInfo.imgFullnameArr.Length > constImgNameListLen){imgNameListLen = constImgNameListLen;}else{imgNameListLen = productInfo.imgFullnameArr.Length;}for (int imgIdx = 0; imgIdx < imgNameListLen; imgIdx++){xlWorkSheet.Cells[curRrowIdx, curColumnIdx + imgIdx] = productInfo.imgFullnameArr[imgIdx];}curColumnIdx = curColumnIdx + imgNameListLen;xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.highestPrice;xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.isOneSellerIsAmazon;xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.reviewNumber;xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.isBestSeller;////http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=ZH-CN&k=k%28MICROSOFT.OFFICE.INTEROP.EXCEL._WORKBOOK.SAVEAS%29;k%28SAVEAS%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV3.5%22%29;k%28DevLang-CSHARP%29&rd=true//xlWorkBook.SaveAs(//    Filename: fullFilename,//    ConflictResolution: XlSaveConflictResolution.xlLocalSessionChanges //The local user's changes are always accepted. //    //FileFormat : Excel.XlFileFormat.xlWorkbookNormal//);//if use above SaveAs -> will popup a window ask you overwrite it or not, even if you have set the ConflictResolution to xlLocalSessionChanges, which should not ask, should directly save
            xlWorkBook.Save();//http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=ZH-CN&k=k%28MICROSOFT.OFFICE.INTEROP.EXCEL._WORKBOOK.CLOSE%29;k%28CLOSE%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV3.5%22%29;k%28DevLang-CSHARP%29&rd=truexlWorkBook.Close(SaveChanges : true);crl.releaseObject(xlWorkSheet);crl.releaseObject(xlWorkBook);crl.releaseObject(xlApp);}

View Code

参考文章

1.C#编程实现Excel文档中搜索文本内容的方法及思路 ,2013-7

2.How to append existing excel file using C# ?

3.MSDN, Workbooks.Open Method

4. C#读取excel文件,并且追加内容到最后一行

转载于:https://www.cnblogs.com/arxive/p/5813901.html

C#中实现对Excel特定文本的搜索相关推荐

  1. 朝花夕拾:Java中实现对EXCEL文件的读取

    在项目中实现读取EXCEL文件中的数据是实现工作项目中数据读取的常用方式.这个对于之前无论写C/C++还是后来写Java来读取txt数据的我来说都是一个新的方式.新的技巧,相信对刚入手的很多小伙伴都是 ...

  2. python对excel表统计视频教程_Python实现对excel文件列表值进行统计的方法

    本文实例讲述了Python实现对excel文件列表值进行统计的方法.分享给大家供大家参考.具体如下: #!/usr/bin/env python #coding=gbk #此PY用来统计一个execl ...

  3. 用python编excel统计表_Python实现对excel文件列表值进行统计的方法

    本文实例讲述了Python实现对excel文件列表值进行统计的方法.分享给大家供大家参考.具体如下: #!/usr/bin/env python #coding=gbk #此PY用来统计一个execl ...

  4. 基于Python的高校勤工俭学工资管理系统——实现对excel表格的数据操作(xwlings库)

    基于Python的高校勤工俭学工资管理系统 1 需求概述 1.1 需求分析 勤工俭学是指学校组织的或学生个人从事的有酬劳动,用以助学.在我国,许多高校借以对学生进行劳动技术教育,培养正确的劳动观点和态 ...

  5. SpringBoot通过WorkBook快速实现对Excel的导入和导出(包括数据校验)

    之前转载过一篇对Excel基本操作相关的文章,这篇文章的浏览量迅速飙升,以至于在我博客的热门文章中排到了第三的位置,不过那篇转载的文章实用性差并且讲解不是很清晰,所以打算趁着今天休息,写一篇关于Spr ...

  6. 使用Python实现对excel数据的处理

    前言 **使用Python实现对excel数据的处理, 预先知识简单介绍 xlrd中 # File_Path是Excel路径,打开Excel工作蒲 workbook = xlrd.open_workb ...

  7. VC实现对Excel表格的操作

    转载请注明原文网址: http://www.cnblogs.com/xianyunhe/archive/2011/09/25/2190485.html 通过VC实现对Excel表格的操作的方法有多种, ...

  8. 用python的openpyxl库实现对excel工作表的自动化操作

    用python的openpyxl库实现对excel工作表的自动化操作 用python的openpyxl库读取excel工作表,批量建立工作表,批量修改工作表标题,批量设置单元格样式,批量调整打印设置. ...

  9. [原创]C#通过引用Office Excel (2007) 组件实现对Excel文件的操作

    对用应用软件来说,将报表转出为Excel文件,进行二次加工,或者根据Excel模版填充数据,是非常常用的.实现对Excel文件的操作,如将报表转出为Excel或根据已有的Excel模版进行填充,有很多 ...

最新文章

  1. 搭建你的嵌入式Vxworks开发环境
  2. python快递费用计算_[Python]简单用Python写个查询快递的程序最后附源代码
  3. 好大夫王航:长尾开发者应尽快接入百度轻应用
  4. Python计算机视觉编程pdf
  5. .net文档生成工具2.0 支持自定义文档生成器【转:http://www.cnblogs.com/lucc/archive/2008/09/05/1284762.html】...
  6. 计算机软考论文分数,信息系统项目管理师论文37分等得分低原因、不及格原因...
  7. 关于浮点数据类型和布尔数据类型以及最后的总结
  8. 用python 控制台打印图片示例
  9. 别让生活 耗尽了你的耐心和向往 你还有诗和远方...
  10. 网站2008服务器32位好还是64位好,win server 2008 32位与64位区别
  11. 百度百科创建个人词条怎么写?
  12. 相册照片直播小程序开发
  13. 中国悍马“猛士”登场,国产电动车为啥掀起了硬派越野风?
  14. js把日期字符串转换成时间戳 阿星小栈
  15. MATLAB-将数据读取/写入excel表格
  16. redis.set方法详解
  17. linux系列之-磁盘空间不足怎么办,磁盘清理方法
  18. 网络安全笔记第三天(window7密码破解,NTFS)
  19. c盘那些文件可以删除
  20. flash文本竖排效果实现(AS3)

热门文章

  1. php sql delete 返回值,delete方法
  2. incon函数图像c语言,[转载]c语言经典题目
  3. php获取数组中,相同键名的键值之和
  4. 「高并发秒杀」mysql数据库引擎区别
  5. linux 脚本select菜单,Shell:如何写一个多选菜单的脚本
  6. python图形用户界面设计报告_19.1 Python图形用户界面开发工具包
  7. 取消管理员取得所有权_企业取得违约补偿款是否一律应缴增值税呢?
  8. oracle 测试数据类型,oracle修改表字段的数据类型测试
  9. 网站seo优化相关性需要了解哪三方面内容?
  10. 网页html是什么语言程序,html是什么