我使用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/