布尔返回true,而excel单元格值之一与使用C#的其他单元格值不匹配

问题描述

我将工作簿1的第一个工作表与wrokook2的第一个工作表进行了比较,然后在比较了第一个工作表的数据后转到第二个工作表。比较工作簿1的第二个工作表与工作簿2的第二个工作表。这是图片

enter image description here

我使用的代码

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);

现在考虑截图

enter image description here

单元格B5的值在两个工作簿中都不匹配。布尔值应返回false。它返回true,资产显示is true通过测试用例。而它应该失败。仅当最后一个单元格值不同时,它才会使测试用例失败。否则它将通过测试用例。

如何解决此问题?我正在使用C#。

解决方法

您可能正在比较对象引用(我认为worksheet2.Cells [j,i] .value是一个对象)。请尝试将其转换为字符串

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

您应该将var转换为string并使用string.Compare吗?我建议调试有关特定行的读取方式。