使用inputstring匹配行中的单元格

我基本上试图从Excel文件中读取,并find该文件中的某个ID号。 现在它打印所有的行作为一个匹配,我想帮助搞清楚为什么。

// input to search for string value = textBox3.Text; // verify the input is the correct format Match match = Regex.Match(value, @".*[0-9].*"); Match myMatch = Regex.Match(value, textBox3.Text); Console.WriteLine(value); foreach (DataRow row in xlsDs.Rows) { if (match.Success && myMatch.Success) { Console.WriteLine(textBox3); Console.Write(row.ItemArray.ToString()); Console.WriteLine("This was found"); } } 

 int rowCount = xlsDs.Rows.Count; 

我仍然使用foreach循环,然后添加一个简单的计数器,并通过counter++每次循环增加它,当你find它时,你可以将该值和数据添加到集合中,以便稍后参考。

foreach比for循环要安全得多,有时候for循环是非常受欢迎的,但是我不认为这是其中的一个。

你可以通过下面的代码来解决它,如果你想匹配一些excel列EG ID的条件把条件放在for循环….因为我想你想匹配值的某些列的Excel ..

 string value = textBox3.Text; Match match = Regex.Match(value, @".*[0-9].*"); Console.WriteLine(value); int TotalRows = xlsDs.Rows.Count; for(int i=0;i<TotalRows;i++) { DataRow row = xlsDs.Rows[i]; String row_Val=row["Cell_Name"].ToString();//Put Cell you want to match IE ID Match myMatch = Regex.Match(row_Val, textBox3.Text); if (match.Success && myMatch.Success) { Console.WriteLine(textBox3); Console.Write(row.ItemArray.ToString()); //Console.WriteLine(row["Cell_Name"]);//if you want to print a specific cell Console.WriteLine("This was found at row "+i); } } 

你的错误不是for vs foreach循环,而是你正在做的匹配。 试试这个。

您也没有正确读取行,您应该只查看所需的一列。 将下面的列variables更改为正确的列。

这和你的代码之间的主要区别是,你想检查迭代中的每一行,然后如果它匹配,打印一行这样说。 这与你最初做的比较,你比较一个string一次,如果这是一个匹配,每行打印一遍又一遍。

 string columnName = "Employee ID"; // change to the correct header // Check the ID from the textbox to make sure it is valid? Match match = Regex.Match(textBox3.Text @".*[0-9].*"); for(int i = 0; i < xlsDs.Rows.Count; i++) { // get the current row DataRow row = xlsDs.Rows[i]; // get the ID from the row string idValue = row[columnName].ToString(); // check if the row value is equal to the textbox entry bool myMatch = idValue.Equals(textBox3.Text); // if both of the above are true, do this if (match.Success && myMatch == true) { Console.Write(idValue); Console.WriteLine(" -This id was found"); } }