Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I Have two Excel files having some contact numbers,Some names are similar in both excel sheets.i want the number which is having same name in both excel sheets ,program in C#..pls anybody reply to this.
Posted

1 solution

The below method compares 2 worksheets in the same workbook and displays the data which are similar.

C#
void CompareExcel()
        {

            string filePath = @"F:\Book2.xlsx";
 
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;

            try
            {
                xlWorkBook = xlApp.Workbooks.Open(filePath, 0, true, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", true, false, 0, true, 0);

                Microsoft.Office.Interop.Excel.Worksheet worksheet1 = (Microsoft.Office.Interop.Excel.Worksheet)xlApp.Worksheets["Sheet1"];
                Microsoft.Office.Interop.Excel.Worksheet worksheet2 = (Microsoft.Office.Interop.Excel.Worksheet)xlApp.Worksheets["Sheet2"];

                int sheet1LastRowCount = worksheet1.UsedRange.Rows.Count;
                int sheet2LastRowCount = worksheet2.UsedRange.Rows.Count;

                for (int i = 2; i < sheet1LastRowCount; i++)
                {
                    for (int j = 2; j < sheet2LastRowCount; j++)
                    {
                        if (worksheet1.Range["B" + i, "B" + i].Value2 == worksheet2.Range["B" + j, "B" + j].Value2)
                        {
                            Console.WriteLine(worksheet1.Range["A" + i, "A" + i].Value2);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                xlApp.Quit();
            }

            
        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900