我很确定我真的很接近这个问题。我在导入的Excel文档中有数千个IP地址。我输入了一个IP,我想要它,所以程序将该IP地址与excel表中最接近的IP地址匹配,然后打印到控制台。我认为我的问题出在我解析工作表的第一个if语句中。任何帮助将不胜感激。我收到一条错误消息Unhandled Exception:System.NullReferenceException:对象引用不是对象的实例。然后它给出了我的excel表的路径,然后是异常,我猜它假设它在第一个if语句。
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 :(得分:0)
可能是因为您声明了范围对象(使用过的行和列) 但随后遍历工作表行(工作表中使用或不使用的所有行)。
试
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
for (int i = 0; i < xlRange.Rows.Count; i++)
...