2017-03-27 60 views
1

我很确定我真的很接近这个想法。我有一个导入的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!"); 
      } 

     } 
+0

是您正确的代码上面?因为在第一个'if'之后你有一个可执行的代码行,而其余的只是一个总是试图运行的不相关的代码块。您可能需要移动'if.'块内的'Console.WriteLine(excelIP)'行。 –

回答

0

这可能是因为您声明范围内的对象(用行和列) 后来通过工作表行迭代(所有行使用或不使用工作表)。

尝试

Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; 
Excel.Range xlRange = xlWorksheet.UsedRange; 

for (int i = 0; i < xlRange.Rows.Count; i++) 

...

+0

不完全,仍然给我与以前相同的处理异常 – LeGreen95

+2

我想我没有看到你的问题,你提到一个异常被抛出。也许尝试更新它更具体? – Muckeypuck

+0

我发现可能缺少的另一件事是迭代通过列。 xlWorksheet.Cells第[i + 1,1] 也许应该是内部的对(INT I = 0,I Muckeypuck

相关问题