打开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文档:

  1.   object filename="";
  2.   object MissingValue=Type.Missing;
  3.   string strKeyWord=""; //指定要搜索的文本,如果有多个,则声明string[]
  4.   Excel.Application ep=new Excel.ApplicationClass();
  5.   Excel.Workbook ew=ep.Workbooks.Open(filename.ToString(),MissingValue,
  6.    MissingValue,MissingValue,MissingValue,
  7.    MissingValue,MissingValue,MissingValue,
  8.    MissingValue,MissingValue,MissingValue,
  9.    MissingValue,MissingValue,MissingValue,
  10.    MissingValue);

2. 准备遍历Excel工作表

2.1 方法1

  1.   Excel.Worksheet ews;
  2.   int iEWSCnt=ew.Worksheets.Count;
  3.   int i=0,j=0;
  4.   Excel.Range oRange;
  5.   object oText=strKeyWord.Trim().ToUpper();
  6.   
  7.   for(i=1;i<=iEWSCnt;i++)
  8.   {
  9.    ews=null;
  10.    ews=(Excel.Worksheet)ew.Worksheets[i];
  11.    oRange=null;
  12.    (Excel.Range)oRange=((Excel.Range)ews.UsedRange).Find(
  13.    oText,MissingValue,MissingValue,
  14.    MissingValue,MissingValue,Excel.XlSearchDirection.xlNext,
  15.    MissingValue,MissingValue,MissingValue);
  16.    if (oRange!=null && oRange.Cells.Rows.Count>=1 && oRange.Cells.Columns.Count>=1)
  17.    {
  18.    MessageBox.Show("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);
  19.    break;
  20.    }
  21.   }

这里要说两个值得注意的地方。一个是遍历工作表的索引,不是从0开始,而是从1开始;另外一个是Find方法的第六个参数 SearchDirection,指定搜索的方向,帮助文档中说这个参数是可选项,但是我用MissingValue如论如何编译不能通过,不知什么原 因,于是显式指定它的默认值xlNext。

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

  1.   bool blFlag=false;
  2.   int iRowCnt=0,iColCnt=0,iBgnRow,iBgnCol; 
  3.   for(m=1;m<=iEWSCnt;m++)
  4.   {
  5.    ews=(Excel.Worksheet)ew.Worksheets[m];
  6.    iRowCnt=0+ews.UsedRange.Cells.Rows.Count;
  7.    iColCnt=0+ews.UsedRange.Cells.Columns.Count;
  8.    iBgnRow=(ews.UsedRange.Cells.Row>1)? ews.UsedRange.Cells.Row-1:ews.UsedRange.Cells.Row;
  9.    iBgnCol=(ews.UsedRange.Cells.Column>1)? ews.UsedRange.Cells.Column-1:ews.UsedRange.Cells.Column;
  10.   
  11.    for(i=iBgnRow;i
  12.    {
  13.    for(j=iBgnCol;j
  14.    {
  15.    strText=((Excel.Range)ews.UsedRange.Cells[i,j]).Text.ToString();
  16.    if (strText.ToUpper().IndexOf(strKeyWord.ToUpper())>=0)
  17.    {
  18.    MessageBox.Show("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);
  19.    }
  20.    }
  21.    }
  22.   }

显然这种方法比第一种繁琐得多,不过这里有一个关于遍历单元格的索引很特别的地方,当工作表中的使用区域UsedRange为单行单列的时候,对 UsedRange中的单元格遍历起始索引值为1,为多行多列的时候,起始索引值为0,不知这是Excel程序设计者出于什么样的考虑?

2.3 方法二补充案例

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

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

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

准备工作

  1. private void createOutputFile(string excelFullFilename)
  2. {
  3. bool isAutoFit = true;
  4. bool isHeaderBold = true;
  5.  
  6. Excel.Application xlApp = new Excel.Application();
  7. Excel.Workbook xlWorkBook;
  8. Excel.Worksheet xlWorkSheet;
  9.  
  10. object misValue = System.Reflection.Missing.Value;
  11. xlApp = new Excel.ApplicationClass();
  12. xlWorkBook = xlApp.Workbooks.Add(misValue);
  13. xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item();
  14.  
  15. const int excelRowHeader = ;
  16. const int excelColumnHeader = ;
  17.  
  18. //save header
  19. int curColumnIdx = + excelColumnHeader;
  20. int rowIdx = + excelRowHeader;
  21.  
  22. xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "Title";
  23. xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "Description";
  24. const int constBullerLen = ;
  25. for (int bulletIdx = ; bulletIdx < constBullerLen; bulletIdx++)
  26. {
  27. int bulletNum = bulletIdx + ;
  28. xlWorkSheet.Cells[rowIdx, curColumnIdx + bulletIdx] = "Bullet" + bulletNum.ToString();
  29. }
  30. curColumnIdx = curColumnIdx + constBullerLen;
  31. const int constImgNameListLen = ;
  32. for (int imgIdx = ; imgIdx < constImgNameListLen; imgIdx++)
  33. {
  34. int imgNum = imgIdx + ;
  35. xlWorkSheet.Cells[rowIdx, curColumnIdx + imgIdx] = "ImageFilename" + imgNum.ToString();
  36. }
  37. curColumnIdx = curColumnIdx + constImgNameListLen;
  38. xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "HighestPrice";
  39. xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "OneSellerIsAmazon";
  40. xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "ReviewNumber";
  41. xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "IsBestSeller";
  42.  
  43. //formatting
  44. //(1) header to bold
  45. if (isHeaderBold)
  46. {
  47. Range headerRow = xlWorkSheet.get_Range("1:1", System.Type.Missing);
  48. headerRow.Font.Bold = true;
  49. }
  50. //(2) auto adjust column width (according to content)
  51. if (isAutoFit)
  52. {
  53. Range allColumn = xlWorkSheet.Columns;
  54. allColumn.AutoFit();
  55. }
  56.  
  57. //output
  58. xlWorkBook.SaveAs(excelFullFilename,
  59. XlFileFormat.xlWorkbookNormal,
  60. misValue,
  61. misValue,
  62. misValue,
  63. misValue,
  64. XlSaveAsAccessMode.xlExclusive,
  65. XlSaveConflictResolution.xlLocalSessionChanges,
  66. misValue,
  67. misValue,
  68. misValue,
  69. misValue);
  70. xlWorkBook.Close(true, misValue, misValue);
  71. xlApp.Quit();
  72.  
  73. crl.releaseObject(xlWorkSheet);
  74. crl.releaseObject(xlWorkBook);
  75. crl.releaseObject(xlApp);
  76. }

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

  1. private void appendInfoToFile(string fullFilename, AmazonProductInfo productInfo)
  2. {
  3. Excel.Application xlApp;
  4. Excel.Workbook xlWorkBook;
  5. Excel.Worksheet xlWorkSheet;
  6. object missingVal = System.Reflection.Missing.Value;
  7.  
  8. xlApp = new Microsoft.Office.Interop.Excel.Application();
  9. //xlApp.Visible = true;
  10. //xlApp.DisplayAlerts = false;
  11.  
  12. //http://msdn.microsoft.com/zh-cn/library/microsoft.office.interop.excel.workbooks.open%28v=office.11%29.aspx
  13. xlWorkBook = xlApp.Workbooks.Open(
  14. Filename : fullFilename,
  15. //UpdateLinks:3,
  16. ReadOnly : false,
  17. //Format : 2, //use Commas as delimiter when open text file
  18. //Password : missingVal,
  19. //WriteResPassword : missingVal,
  20. //IgnoreReadOnlyRecommended: false, //when save to readonly, will notice you
  21. Origin: Excel.XlPlatform.xlWindows, //xlMacintosh/xlWindows/xlMSDOS
  22. //Delimiter: ",", // usefule when is text file
  23. Editable : true,
  24. Notify : false,
  25. //Converter: missingVal,
  26. AddToMru: true, //True to add this workbook to the list of recently used files
  27. Local: true,
  28. CorruptLoad: missingVal //xlNormalLoad/xlRepairFile/xlExtractData
  29. );
  30.  
  31. //Get the first sheet
  32. xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(); //also can get by sheet name
  33. Excel.Range range = xlWorkSheet.UsedRange;
  34. //int usedColCount = range.Columns.Count;
  35. int usedRowCount = range.Rows.Count;
  36.  
  37. const int excelRowHeader = ;
  38. const int excelColumnHeader = ;
  39.  
  40. //int curColumnIdx = usedColCount + excelColumnHeader;
  41. int curColumnIdx = + excelColumnHeader; //start from column begin
  42. int curRrowIdx = usedRowCount + excelRowHeader; // !!! here must added buildin excelRowHeader=1, otherwise will overwrite previous (added title or whole row value)
  43.  
  44. xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.title;
  45. xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.description;
  46.  
  47. const int constBullerLen = ;
  48. int bulletListLen = ;
  49. if (productInfo.bulletArr.Length > constBullerLen)
  50. {
  51. bulletListLen = constBullerLen;
  52. }
  53. else
  54. {
  55. bulletListLen = productInfo.bulletArr.Length;
  56. }
  57. for (int bulletIdx = ; bulletIdx < bulletListLen; bulletIdx++)
  58. {
  59. xlWorkSheet.Cells[curRrowIdx, curColumnIdx + bulletIdx] = productInfo.bulletArr[bulletIdx];
  60. }
  61. curColumnIdx = curColumnIdx + bulletListLen;
  62.  
  63. const int constImgNameListLen = ;
  64. int imgNameListLen = ;
  65. if (productInfo.imgFullnameArr.Length > constImgNameListLen)
  66. {
  67. imgNameListLen = constImgNameListLen;
  68. }
  69. else
  70. {
  71. imgNameListLen = productInfo.imgFullnameArr.Length;
  72. }
  73. for (int imgIdx = ; imgIdx < imgNameListLen; imgIdx++)
  74. {
  75. xlWorkSheet.Cells[curRrowIdx, curColumnIdx + imgIdx] = productInfo.imgFullnameArr[imgIdx];
  76. }
  77. curColumnIdx = curColumnIdx + imgNameListLen;
  78.  
  79. xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.highestPrice;
  80. xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.isOneSellerIsAmazon;
  81. xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.reviewNumber;
  82. xlWorkSheet.Cells[curRrowIdx, curColumnIdx++] = productInfo.isBestSeller;
  83.  
  84. ////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
  85. //xlWorkBook.SaveAs(
  86. // Filename: fullFilename,
  87. // ConflictResolution: XlSaveConflictResolution.xlLocalSessionChanges //The local user's changes are always accepted.
  88. // //FileFormat : Excel.XlFileFormat.xlWorkbookNormal
  89. //);
  90.  
  91. //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
  92. xlWorkBook.Save();
  93.  
  94. //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=true
  95. xlWorkBook.Close(SaveChanges : true);
  96.  
  97. crl.releaseObject(xlWorkSheet);
  98. crl.releaseObject(xlWorkBook);
  99. crl.releaseObject(xlApp);
  100. }

参考文章

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

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

3.MSDN, Workbooks.Open Method

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

C#中实现对Excel特定文本的搜索的更多相关文章

  1. Android平台中实现对XML的三种解析方式

    本文介绍在Android平台中实现对XML的三种解析方式. XML在各种开发中都广泛应用,Android也不例外.作为承载数据的一个重要角色,如何读写XML成为Android开发中一项重要的技能. 在 ...

  2. JAVA-----基于POI实现对Excel导入

    在日常项目开发中, 数据录入和导出是十分普遍的需求,因此,导入导出也成为了开发中一个经典的功能.数据导出的格式一般是excel或者pdf,而批量导入的信息一般是借助excel来减轻工作量,提高效率. ...

  3. 在应用程序中实现对NandFlash的操作

    以TC58NVG2S3ETA00 为例: 下面是它的一些物理参数: 图一 图二 图三 图四 图五 图6-0 图6-1 说明一下,在图6-1中中间的那个布局表可以看做是实际的NandFlash一页数据的 ...

  4. C++中实现对map按照value值进行排序 - 菜鸟变身记 - 51CTO技术博客

    C++中实现对map按照value值进行排序 - 菜鸟变身记 - 51CTO技术博客 C++中实现对map按照value值进行排序 2012-03-15 15:32:36 标签:map 职场 休闲 排 ...

  5. 通过vb.net 和NPOI实现对excel的读操作

    通过vb.net 和NPOI实现对excel的读操作,很久很久前用过vb,这次朋友的代码是vb.net写的需要一个excel的操作, 就顾着着实现功能了,大家凑合着看吧 Option Explicit ...

  6. Python中实现对list做减法操作介绍

    Python中实现对list做减法操作介绍 这篇文章主要介绍了Python中实现对list做减法操作介绍,需要的朋友可以参考下 问题描述:假设我有这样两个list, 一个是list1,list1 = ...

  7. WPF: 在 MVVM 设计中实现对 ListViewItem 双击事件的响应

    ListView 控件最常用的事件是 SelectionChanged:如果采用 MVVM 模式来设计 WPF 应用,通常,我们可以使用行为(如 InvokeCommandAction)并结合命令来实 ...

  8. ios中实现对UItextField,UITextView等输入框的字数限制

    本文转载至 http://blog.sina.com.cn/s/blog_9bf272cf01013lsd.html 2011-10-05 16:48 533人阅读 评论(0) 收藏 举报 1.    ...

  9. 在Asp.Net MVC中使用NPOI插件实现对Excel的操作(导入,导出,合并单元格,设置样式,输入公式)

    前言 NPOI 是 POI 项目的.NET版本,它不使用 Office COM 组件,不需要安装 Microsoft Office,目前支持 Office 2003 和 2007 版本. 1.整个Ex ...

随机推荐

  1. Girls: different perspectives to consider

    Girls: different perspectives to consider成为极品女人的十大要素The point of articles such as these isn't to dic ...

  2. 也谈SWD接口协议分析

    这几日看到坛里有几个关于SWD协议相关的文章,自己也尝试了下,有点体会,也有些疑惑,写出来与大家分享和交流下.    以下我的模拟SWD接口的板子简称为Host,目标MCU(即我要连接的板子)简称为T ...

  3. iOS中检测硬件和传感器

    首先要知道,你需要查看所需的硬件或传感器是否存在,而不是假设设备有哪些功能.举个例子,你不能假设只有iPhone才有麦克风,而应该使用API来查看麦克风是否存在.下面这段代码的第一个优势在于,它能自动 ...

  4. 大众点评开源分布式监控平台 CAT 深度剖析

    一.CAT介绍 CAT系统原型和理念来源于eBay的CAL的系统,CAT系统第一代设计者吴其敏在eBay工作长达十几年,对CAL系统有深刻的理解.CAT不仅增强了CAL系统核心模型,还添加了更丰富的报 ...

  5. Java WEB安全问题及解决方案

    1.弱口令漏洞   解决方案:最好使用至少6位的数字.字母及特殊字符组合作为密码.数据库不要存储明文密码,应存储MD5加密后的密文,由于目前普通的MD5加密已经可以被破解,最好可以多重MD5加密.   ...

  6. Java中获取完整的url

    Java中获得完整的URl字符串 HttpServletRequest httpRequest=(HttpServletRequest)request; String strBackUrl = &qu ...

  7. bat 脚本传递参数测试

    start  CommissionMQMonitorService.exe   MMM 命令   执行器                                           参数

  8. 使用 httpkit 来替代 jetty

    Compojure 是一个基于 ring 的上层web开发框架.在 lein new compojure my-app 生成的项目中,默认是启用 jetty 服务器的,最近用到了 http-kit 中 ...

  9. platform设备驱动全透析

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://21cnbao.blog.51cto.com/109393/337609 1.1 ...

  10. leetcode:Insertion Sort List

    Sort a linked list using insertion sort. 分析:此题要求在链表上实现插入排序. 思路:插入排序是一种O(n^2)复杂度的算法,基本想法就是每次循环找到一个元素在 ...