将字符串值与导入的Excel电子表格中的值匹配

时间:2017-03-24 18:48:51

标签: c# excel ip subnet

我正在尝试输入一个与我的excel spreadhseet中的IP匹配的IP地址。它开始在DataRow row = xlWorksheet.Rows [i]中崩溃;线。我需要循环,因为我正在处理成千上万的ip和子网,它需要与CLOSEST ip匹配。我想它可能没有拿起电子表格中的所有单元格?因为输入的IP地址是一个字符串变量,当我使用我注释掉的代码来显示所有列时,它会获得所有列。!

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)
        {
            int rCnt = 0;
            int cCnt = 0;
            string str;


            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;
            Excel.Range currentFind = null;
            Excel.Range firstFind = null;
            Excel.XlFindLookIn xlValues;
            Excel.XlLookAt xlPart;

            string columnSubnet = "Network"; // change to the correct header

            Match match = Regex.Match(columnSubnet, @".*[0-3148].*");
            for (int i = 0; i < xlWorksheet.Rows.Count; i++)
            {
                // get the current row
                DataRow row = xlWorksheet.Rows[i];
                // get the ID from the row
                string idValue = row[columnSubnet].ToString();
                // check if the row value is equal to the textbox entry
                bool myMatch = idValue.Equals(addr);
                // if both of the above are true, do this
                if (match.Success && myMatch == true)
                {
                    Console.Write(idValue);
                    Console.WriteLine(" -This id was found");
                }

1 个答案:

答案 0 :(得分:1)

您的代码中有一些与对象类型有关的问题。

首先,变量addr的类型为IPAddress,但稍后您会尝试将值与字符串进行比较。字符串对象永远不会等于IPAddress对象。您需要将传入的IP string解析为IPAddress对象本身,如下所示:

IPAddress idValue = IPAddress.Parse(row[columnSubnet].ToString());

其次,对于您声明的问题,xlWorksheet.Rows[i]会为您提供Range个对象,而不是DataRow个对象。您的代码没有显示数据行被保存在任何地方,所以我假设您只是用它来获取您的价值。您可以通过这种方式直接提取所需的值,而无需检查正则表达式:(这假设您知道列索引)

for (int i = 0; i < xlWorksheet.Rows.Count; i++)
{   
    IPAddress excelIP;
    if (IPAddress.TryParse(xlWorksheet.Cells[i + 1, <ip column index>].Value.ToString(), out excelIP)) 
    {
        Console.Write(excelIP.toString());
        Console.WriteLine(" -This id was found");
    }
}