将string值匹配到导入的Excel表单元格

我很确定我真的接近了这个想法。 我有一个导入的Excel文档中的数千个IP地址。 我input一个IP,我想要它,所以程序匹配的IP地址与Excel表中最接近的IP地址,然后打印到控制台。 我认为我的问题是在我parsing工作表的第一个if语句中。 任何帮助将不胜感激。 我得到一个错误消息未处理的exception:System.NullReferenceException:对象引用不是一个对象的实例。 然后给出我的excel表单的path,后面是我认为是第一个if语句的exception。

using 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) { 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:\subnets.xlsx"); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; bool foundIP = false; IPAddress excelIP = IPAddress.Parse("8.8.8.8"); for (int i = 0; i < xlWorksheet.Rows.Count; i++) { if (IPAddress.TryParse(xlWorksheet.Cells[i + 1, 1].Value.ToString(), out excelIP)) Console.WriteLine(excelIP); { // Compare the IP address we found with the one we're looking for if (excelIP.Equals(addr)) { foundIP = true; break; } } } if (foundIP) { Console.WriteLine("Found the IP address!"); Console.WriteLine(excelIP); } else { Console.WriteLine("Found the IP address!"); } } 

这可能是因为您声明范围对象(使用的行和列),然后遍历工作表行(所有行使用或不在工作表中)。

尝试

 Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; for (int i = 0; i < xlRange.Rows.Count; i++)