Bool returns true whereas one of the excel cell value does not matches to other cell value using C#

  • Thread starter Thread starter Mehwish 001
  • Start date Start date
M

Mehwish 001

Guest
I compared 1st worksheet of workbook1 to 1st worksheet of wrokook2 and then after comparing data of first worksheet go to second work sheet. Compare second worksheet of workbook1 to the second worksheet of workbook2.

The code I used is


public bool CompareFiles(string filePath1, string filePath2)
{

bool result = false;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
excel.DisplayAlerts = false;

//Open files to compare
Microsoft.Office.Interop.Excel.Workbook workbook1 = excel.Workbooks.Open(filePath1);
Microsoft.Office.Interop.Excel.Workbook workbook2 = excel.Workbooks.Open(filePath2);

int numSheets = workbook2.Sheets.Count;

for (int a = 1; a <= numSheets; a++)
{
//Open sheets to grab values from
Microsoft.Office.Interop.Excel.Worksheet worksheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook1.Sheets[a];
Microsoft.Office.Interop.Excel.Worksheet worksheet2 = (Microsoft.Office.Interop.Excel.Worksheet)workbook2.Sheets[a];

//Get the used range of cells
Microsoft.Office.Interop.Excel.Range range = worksheet2.UsedRange;
int maxColumns = range.Columns.Count;
int maxRows = range.Rows.Count;

//Check that each cell matches
for (int i = 1; i <= maxColumns; i++)
{
for (int j = 1; j <= maxRows; j++)
{
var value = range.Cells[maxRows, maxColumns].Value2;
if (worksheet1.Cells[j, i].value== worksheet2.Cells[j, i].value)
{

result = true;
}
else

result = false;
}

}


}

workbook1.Close();
workbook2.Close();
excel.Quit();

return result;
}
Assert.IsTrue(CompareFiles(filepath1 , filepath2);

now consider there is data in excel sheet2 in cell A1 to C8. The value of cell B5 in worksheet2 of workbook1 does not match with the value of cell B5 in worksheet2 of workbook2.The value in cell B5 in worksheet2 of workbook1 is "Case" whereas value of cell B5 in worksheet2 of workbook2 is "Ca"

The bool should return false. Where as it is returning true and asset is showing is true passing the testcase. Whereas it should get failed. How can I resolve this issue? I am using C#.

I have tried converting to string like

if ((string)worksheet1.Cells[j, i].value== (string)worksheet2.Cells[j, i].value)


But it shows 'Cannot convert type 'double' to 'string''.

How can i resolve the issue?

Continue reading...
 
Back
Top