我很確定我真的很接近這個想法。我有一個導入的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)'行。 –