C#中实现对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对象中的所有行列。实际开发中,用第二
种方法时发现了一个特别的现象,所以第二种方法也准备详细记述一下。
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(); const int excelRowHeader = ;
const int excelColumnHeader = ; //save header
int curColumnIdx = + excelColumnHeader;
int rowIdx = + excelRowHeader; xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "Title";
xlWorkSheet.Cells[rowIdx, curColumnIdx++] = "Description";
const int constBullerLen = ;
for (int bulletIdx = ; bulletIdx < constBullerLen; bulletIdx++)
{
int bulletNum = bulletIdx + ;
xlWorkSheet.Cells[rowIdx, curColumnIdx + bulletIdx] = "Bullet" + bulletNum.ToString();
}
curColumnIdx = curColumnIdx + constBullerLen;
const int constImgNameListLen = ;
for (int imgIdx = ; imgIdx < constImgNameListLen; imgIdx++)
{
int imgNum = imgIdx + ;
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 bold
if (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);
}
现在需要用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.aspx
xlWorkBook = 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 you
Origin: Excel.XlPlatform.xlWindows, //xlMacintosh/xlWindows/xlMSDOS
//Delimiter: ",", // usefule when is text file
Editable : true,
Notify : false,
//Converter: missingVal,
AddToMru: true, //True to add this workbook to the list of recently used files
Local: true,
CorruptLoad: missingVal //xlNormalLoad/xlRepairFile/xlExtractData
); //Get the first sheet
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(); //also can get by sheet name
Excel.Range range = xlWorkSheet.UsedRange;
//int usedColCount = range.Columns.Count;
int usedRowCount = range.Rows.Count; const int excelRowHeader = ;
const int excelColumnHeader = ; //int curColumnIdx = usedColCount + excelColumnHeader;
int curColumnIdx = + excelColumnHeader; //start from column begin
int 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 = ;
int bulletListLen = ;
if (productInfo.bulletArr.Length > constBullerLen)
{
bulletListLen = constBullerLen;
}
else
{
bulletListLen = productInfo.bulletArr.Length;
}
for (int bulletIdx = ; bulletIdx < bulletListLen; bulletIdx++)
{
xlWorkSheet.Cells[curRrowIdx, curColumnIdx + bulletIdx] = productInfo.bulletArr[bulletIdx];
}
curColumnIdx = curColumnIdx + bulletListLen; const int constImgNameListLen = ;
int imgNameListLen = ;
if (productInfo.imgFullnameArr.Length > constImgNameListLen)
{
imgNameListLen = constImgNameListLen;
}
else
{
imgNameListLen = productInfo.imgFullnameArr.Length;
}
for (int imgIdx = ; 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=true
xlWorkBook.Close(SaveChanges : true); crl.releaseObject(xlWorkSheet);
crl.releaseObject(xlWorkBook);
crl.releaseObject(xlApp);
}
参考文章
1.C#编程实现Excel文档中搜索文本内容的方法及思路 ,2013-7
2.How to append existing excel file using C# ?
3.MSDN, Workbooks.Open Method
C#中实现对Excel特定文本的搜索的更多相关文章
- Android平台中实现对XML的三种解析方式
本文介绍在Android平台中实现对XML的三种解析方式. XML在各种开发中都广泛应用,Android也不例外.作为承载数据的一个重要角色,如何读写XML成为Android开发中一项重要的技能. 在 ...
- JAVA-----基于POI实现对Excel导入
在日常项目开发中, 数据录入和导出是十分普遍的需求,因此,导入导出也成为了开发中一个经典的功能.数据导出的格式一般是excel或者pdf,而批量导入的信息一般是借助excel来减轻工作量,提高效率. ...
- 在应用程序中实现对NandFlash的操作
以TC58NVG2S3ETA00 为例: 下面是它的一些物理参数: 图一 图二 图三 图四 图五 图6-0 图6-1 说明一下,在图6-1中中间的那个布局表可以看做是实际的NandFlash一页数据的 ...
- C++中实现对map按照value值进行排序 - 菜鸟变身记 - 51CTO技术博客
C++中实现对map按照value值进行排序 - 菜鸟变身记 - 51CTO技术博客 C++中实现对map按照value值进行排序 2012-03-15 15:32:36 标签:map 职场 休闲 排 ...
- 通过vb.net 和NPOI实现对excel的读操作
通过vb.net 和NPOI实现对excel的读操作,很久很久前用过vb,这次朋友的代码是vb.net写的需要一个excel的操作, 就顾着着实现功能了,大家凑合着看吧 Option Explicit ...
- Python中实现对list做减法操作介绍
Python中实现对list做减法操作介绍 这篇文章主要介绍了Python中实现对list做减法操作介绍,需要的朋友可以参考下 问题描述:假设我有这样两个list, 一个是list1,list1 = ...
- WPF: 在 MVVM 设计中实现对 ListViewItem 双击事件的响应
ListView 控件最常用的事件是 SelectionChanged:如果采用 MVVM 模式来设计 WPF 应用,通常,我们可以使用行为(如 InvokeCommandAction)并结合命令来实 ...
- ios中实现对UItextField,UITextView等输入框的字数限制
本文转载至 http://blog.sina.com.cn/s/blog_9bf272cf01013lsd.html 2011-10-05 16:48 533人阅读 评论(0) 收藏 举报 1. ...
- 在Asp.Net MVC中使用NPOI插件实现对Excel的操作(导入,导出,合并单元格,设置样式,输入公式)
前言 NPOI 是 POI 项目的.NET版本,它不使用 Office COM 组件,不需要安装 Microsoft Office,目前支持 Office 2003 和 2007 版本. 1.整个Ex ...
随机推荐
- mmap 的理解
mmap 的理解 采用共享内存通信的一个显而易见的好处 是效率高,因为进程可以直接读写内存,而不需要任何数据的拷贝.对于像管道和消息队列等通信方式,则需要在内核和用户空间进行四次的数据拷贝,而共享内存 ...
- C++名字空间/C++命名空间
0.序言 名字空间是C++提供的一种解决符号名字冲突的方法. 一个命令空间是一个作用域,在不同名字空间中命名相同的符号代表不同的实体. 通常,利用定义名字空间的办法,可以使模块划分更加方便,减少模块间 ...
- hive-学习笔记
1.hive模糊搜索表 show tables like '*name*'; 2.查看表结构信息 desc formatted table_name; desc table_name; 3.查看 ...
- JavaWeb项目开发案例精粹-第4章博客网站系统-006View层
1.showAllArticle.jsp <%@ page language="java" contentType="text/html; charset=gb23 ...
- Qt之获取本机网络信息(MAC, IP等等,很全)
经常使用命令行来查看一些计算机的配置信息. 1.首先按住键盘上的“开始键+R键”,然后在弹出的对话框中输入“CMD”,回车 另外,还可以依次点击 开始>所有程序>附件>命令提示符 2 ...
- 常用加密算法的Java实现总结
常用加密算法的Java实现(一) ——单向加密算法MD5和SHA 1.Java的安全体系架构 1.1 Java的安全体系架构介绍 Java中为安全框架提供类和接口.JDK 安全 A ...
- Socket基础编程
地址结构sockaddr_in 其中包含:IP地址,端口号,协议族推荐使用sockaddr_in,而不建议使用sockaddrsockaddr_in与sockaddr是等价的,但sockaddr_in ...
- zf2 安装
下载实例程序 ZendSkeletonApplication 解压至D:\xampp\htdocs并重命名为ZendSkeletonApplication 下载Zend Framework 2.0最新 ...
- google protobuf使用
下载的是github上的:https://github.com/google/protobuf If you get the source from github, you need to gener ...
- hdu 4565 So Easy!(矩阵+快速幂)
题目大意:就是给出a,b,n,m:让你求s(n); 解题思路:因为n很可能很大,所以一步一步的乘肯定会超时,我建议看代码之前,先看一下快速幂和矩阵快速幂,这样看起来就比较容易,这里我直接贴别人的推导, ...