[英]How to match exact string value or closest match with excel column cell
我有一個代碼,我輸入IP地址,然后它將循環並搜索該IP的excel列中最接近的匹配。 它只是循環每個IP,如何將參數與IP匹配?
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:\Users\subnets.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
for (int i = 0; i < xlWorksheet.Rows.Count; i++)
{
IPAddress excelIP = IPAddress.Parse("8.8.8.8");
if (IPAddress.TryParse(xlWorksheet.Cells[i + 1, 1].Value.ToString(), out excelIP))
{
Console.Write(excelIP.ToString());
Console.WriteLine(" -This id was found");
}
}
}
將您找到的那個與您正在搜索的那個進行比較(您也可以將excelIP
的聲明移出循環 - 您只需要聲明一次)。 我還創建了一個標志,以防你需要根據在退出循環后是否找到所需的IP來執行某些操作:
bool foundIP = false;
IPAddress excelIP;
for (int i = 0; i < xlWorksheet.Rows.Count; i++)
{
if (IPAddress.TryParse(xlWorksheet.Cells[i + 1, 1].Value.ToString(), out excelIP))
{
// Compare the IP address we found with the one we're looking for
if (excelIP.Equals(addr))
{
foundIP = true;
break; // Exit the for loop since we found it
}
}
}
if (foundIP)
{
Console.WriteLine("Found the IP address!");
// If you need to do something with the IP, you can use either excelIP
// or addr, since they are both the same at this point
}
else
{
Console.WriteLine("IP address was not found.");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.