首页 > 技术文章 > Microsoft.Office.Interop.Excel Find 操作

fengye87626 2019-07-10 10:06 原文

public void SearchLoactions(string filepath, int start, int end ,string expectvalue) { if (end >= start) { Application xlApp = new Application(); try { if (!File.Exists(filepath)) throw new FileNotFoundException("Can not find the file, please check whether the file exists"); var xlWorkBook = xlApp.Workbooks.Open(filepath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); //code that fails or just returns bad ansvers: //This code just returns a list of worksheets //var worksheetlist = xlWorkBook.Worksheets.Cast().ToList(); var sheet = (Worksheet)xlApp.ActiveWorkbook.Worksheets[2]; var rgUsed = sheet.get_Range("S7:BZ105"); var rgFound = sheet.Range["S7", "BZ105"].Cells.Find(expectvalue, Type.Missing, XlFindLookIn.xlValues, XlLookAt.xlPart, XlSearchOrder.xlByRows, XlSearchDirection.xlNext, Type.Missing, Type.Missing, Type.Missing); Range rgTmp = rgFound; do { var item = rgTmp.get_Value(); Console.WriteLine("Value:" + item); int iRowNum = rgTmp.Row; Console.WriteLine("Row:"+iRowNum); int iColNum = rgTmp.Column; Console.WriteLine("Column:"+iColNum); rgTmp = rgUsed.FindNext(rgTmp); Console.WriteLine("---------------------------"); } while (rgTmp.Address != rgFound.Address);//记录第一个找到的range地址,当下一个单元格的地址与第一个相同,则跳出。 } catch (Exception ex) { Console.WriteLine(ex.Message); Debug.WriteLine(ex.Message); } finally { xlApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp); xlApp = null; } //return itemlst; } else { //return null; } }

推荐阅读