Raspi Surya
Raspi Surya

Reputation: 315

find exact string in excel sheet in C# program

I am using c# program to search a text in my excel sheet. i have excel sheet called "MASTER" and in that sheet, there are a lot of text in column B. I want to look for text "apple" inside column B. here is my code:

Excel.Worksheet workSheet;
workSheet = (Excel.Worksheet)xlWorkBook.Worksheets["MASTER"];
string result;
string utterance = "apples";

range1 = workSheet.Columns["B:B"] as Excel.Range;
Excel.Range findRange 
findRange = range1.Find(utterance);
result = (string) (range2.Cells[findRange1.Row, 2] as Excel.Range).Value2;

it can search through the column B for input utterance "apples". however, in that column, there are a lot of apples. "applepie", "applejam","apple", etc. and the result from above code is "applepie". I think it because it just find the text contain "apple". my question is how to make it find the exact string so the output will be "apple" from column B?

Upvotes: 1

Views: 12151

Answers (2)

Kais
Kais

Reputation: 117

You can use the method Split, to treat every word as an array element

range1 = workSheet.Columns["B:B"] as Excel.Range;
var words = range1.Split(' ');
foreach(var word in words)
{
    if (word == utterance)
        Console.WriteLine(word);
}

Upvotes: 0

Paweł Dyl
Paweł Dyl

Reputation: 9143

Range.Find has many other arguments (see documentation), especially LookAt, see demo below:

var app = new Excel.Application();
var workbook = app.Workbooks.Open("C:\\Path\\File.xlsx");
var sheet = workbook.Worksheets["MASTER"];
var range = (Excel.Range)sheet.Columns["B:B"];
var result = range.Find("apples", LookAt: Excel.XlLookAt.xlWhole);
var address = result.Address;//cell address
var value = result.Value2;//cell value
//close or do something else

Upvotes: 4

Related Questions