简体   繁体   English

如何匹配精确的字符串值或最接近的匹配excel列单元格

[英]How to match exact string value or closest match with excel column cell

I have a code where I enter the IP address and then it will loop and search for the closest match in the excel column for that IP. 我有一个代码,我输入IP地址,然后它将循环并搜索该IP的excel列中最接近的匹配。 It just loops every IP, how do I put an argument where it matches that IP? 它只是循环每个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");                        
                }
            }    
        }

Compare the one you found with the one you're searching for (you can also move the declaration of excelIP out of the loop - you only need to declare it once). 将您找到的那个与您正在搜索的那个进行比较(您也可以将excelIP的声明移出循环 - 您只需要声明一次)。 I also created a flag in case you need to take some action based on whether or not you found the IP you were looking for after you exit the loop: 我还创建了一个标志,以防你需要根据在退出循环后是否找到所需的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM