[英]Matching a string value with a cell with the same or close to same value in an excel spreadsheet
[英]Matching a string value to an imported excel sheet cell
我很確定我真的很接近這個問題。 我在導入的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!");
}
}
這可能是因為您聲明了范圍對象(使用過的行和列),但隨后遍歷工作表行(工作表中使用或不使用的所有行)。
嘗試
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
for (int i = 0; i < xlRange.Rows.Count; i++)
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.