我很确定我真的很接近这个想法。我有一个导入的excel文档中有数千个IP地址。我输入一个IP,然后我需要它,以便程序将该IP地址与Excel表中最近的IP地址相匹配,然后打印到控制台。我认为我的问题出现在我解析工作表的第一条if语句中。任何帮助将不胜感激。我收到一条错误消息未处理的异常:System.NullReferenceException:对象引用不是对象的一个实例。然后,它给出了我的Excel表格的路径,后面是我认为它是第一个if语句的异常。将字符串值匹配到导入的Excel单元格
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!");
}
}
是您正确的代码上面?因为在第一个'if'之后你有一个可执行的代码行,而其余的只是一个总是试图运行的不相关的代码块。您可能需要移动'if.'块内的'Console.WriteLine(excelIP)'行。 –