将string值匹配到导入的Excel电子表格中的值

我正在尝试input一个IP地址,将匹配我的Excel中的一个IP spreadhseet。 它开始崩溃在DataRow行= xlWorksheet.Rows [i]; 线。 我需要它循环,因为我正在处理数以千计的IP和子网,并且它需要匹配CLOSEST IP。 我在想这可能不会在电子表格中提取所有单元格? 因为input的IP地址是一个stringvariables,当我使用我注释的代码来显示所有列时,它将获得所有的列。

System; using System.Net; using Microsoft.Office.Interop.Excel; using Excel = Microsoft.Office.Interop.Excel; using System.Data.OleDb; using System.Data; using System.Runtime.InteropServices; using System.Text.RegularExpressions; namespace Investigations { class Program { static void Main(string[] args) { int rCnt = 0; int cCnt = 0; string str; IPAddress addr = IPAddress.Parse("8.8.8.8"); IPHostEntry entry = Dns.GetHostEntry(addr); Console.WriteLine("IP Address: " + addr); Console.WriteLine("Host Name: " + entry.HostName); Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\subnets.xlsx"); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; Excel.Range currentFind = null; Excel.Range firstFind = null; Excel.XlFindLookIn xlValues; Excel.XlLookAt xlPart; string columnSubnet = "Network"; // change to the correct header Match match = Regex.Match(columnSubnet, @".*[0-3148].*"); for (int i = 0; i < xlWorksheet.Rows.Count; i++) { // get the current row DataRow row = xlWorksheet.Rows[i]; // get the ID from the row string idValue = row[columnSubnet].ToString(); // check if the row value is equal to the textbox entry bool myMatch = idValue.Equals(addr); // if both of the above are true, do this if (match.Success && myMatch == true) { Console.Write(idValue); Console.WriteLine(" -This id was found"); } 

代码中有几个关于对象types的问题。

首先closuresvariablesaddr的types是IPAddress但后来你试图将这个值与一个string进行比较。 一个string对象永远不会等于一个IPAddress对象。 您需要将传入的ip stringparsing为一个IPAddress对象,如下所示:

 IPAddress idValue = IPAddress.Parse(row[columnSubnet].ToString()); 

其次,关于你所说的问题, xlWorksheet.Rows[i]给你一个Range对象,而不是DataRow对象。 你的代码不会显示那个datarow被保存在任何地方,所以我假设你只是用它来获得你的价值。 你可以通过这种方式直接获取所需的值,而不必检查正则expression式:(假定你知道列索引)

 for (int i = 0; i < xlWorksheet.Rows.Count; i++) { IPAddress excelIP; if (IPAddress.TryParse(xlWorksheet.Cells[i + 1, <ip column index>].Value.ToString(), out excelIP)) { Console.Write(excelIP.toString()); Console.WriteLine(" -This id was found"); } }