【发布时间】:2017-08-21 21:44:35
【问题描述】:
我正在尝试将输入的 IP 地址与 Excel 电子表格中的单元格匹配。我输入 IP,然后一个变量在 Excel 电子表格中搜索最接近的匹配项。我的代码的问题是 excelIP 变量,无论是什么都只存储我的电子表格中的第一个单元格值,因此永远不会匹配。
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\Subnets1.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
for(int i = 0; i < xlWorksheet.Rows.Count; i++)
{
IPAddress excelIP;
if (IPAddress.TryParse(xlWorksheet.Cells[i + 1, 1].Value.ToString(), out excelIP))
{
if (excelIP.ToString().Equals(addr))
{
Console.Write(excelIP.ToString());
Console.WriteLine(" -This id was found");
}
else
{
Console.WriteLine("No Match ");
break;
}
}
}
}
}
}
【问题讨论】: