gpt4 book ai didi

c# - 使用断言比较两个 excel 文件

转载 作者:太空狗 更新时间:2023-10-30 01:32:04 25 4
gpt4 key购买 nike

我正在使用 Visual Studio 创建一个自动化测试,该测试会创建两个 Excel 工作表。作为最后的检查,我需要比较这两个 excel 表的内容并确保它们相等。有什么方法可以用断言做到这一点吗?

类似于 Assert.AreEqual(file1, file2);?

如有任何帮助或指导,我们将不胜感激!

最佳答案

感谢Mangist寻求指导。我写了以下内容来比较两个 excel 文件:

public bool compareFiles(string filePath1, string filePath2)
{
bool result = false;
Excel.Application excel = new Excel.Application();

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

//Open sheets to grab values from
Excel.Worksheet worksheet1 = (Excel.Worksheet)workbook1.Sheets[1];
Excel.Worksheet worksheet2 = (Excel.Worksheet)workbook2.Sheets[1];

//Get the used range of cells
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++)
{
if (worksheet1.Cells[j, i].Value == worksheet2.Cells[j, i].Value)
{
result = true;
}
else
result = false;
}
}


//Close the workbooks
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(range);
Marshal.ReleaseComObject(worksheet1);
Marshal.ReleaseComObject(worksheet2);
workbook1.Close();
workbook2.Close();
excel.Quit();
Marshal.ReleaseComObject(excel);

//Tell us if it is true or false
return result;
}

并使用断言来检查结果:

Assert.IsTrue(compareFiles(testFile, compareFile), "Output files do not match.");

关于c# - 使用断言比较两个 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38399359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com