2017-03-27 144 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

相關問題