简体   繁体   English

Selenium C# 从 Excel 读取数据,用于基于 SheetName 的数据驱动测试

[英]Selenium C# reading data from Excel for data driven testing Based On SheetName

I am trying to perform Data driven testing by loading client codes from Excel file to login and perform other operation.I am trying to iterate my test for all clients in the User_Name column.我正在尝试通过从 Excel 文件加载客户端代码以登录并执行其他操作来执行数据驱动测试。我正在尝试为 User_Name 列中的所有客户端迭代我的测试。 I only need to read Data From SheetName, right now i have Contstant SheetName (i,e sheet1), wanted to add SheetName Parameter我只需要从 SheetName 读取数据,现在我有 Contstant SheetName(即 sheet1),想添加 SheetName 参数

Any help with this would be much appreciated thank you.对此的任何帮助将不胜感激,谢谢。

I am using ExcelDataReader v3.4.0, ExcelDataReader.DataSet v3.4.0, selenium Webdriver v3.11.0我正在使用 ExcelDataReader v3.4.0、ExcelDataReader.DataSet v3.4.0、selenium Webdriver v3.11.0

My Excel Generic Code is Below:我的 Excel 通用代码如下:

```
    using ExcelDataReader;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Runtime.Remoting.Messaging;
    using System.Text;
    using System.Threading.Tasks;

    namespace MyDemoAutomation
    {
     public class ExcelUtil
     {
     public DataTable ExcelToDatable(string fileName)
        {
        // open file and returns as stream

        FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
        // create openXmlReader via ExcelReaderFactory
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        //Set the first row as column name
      var result1 = excelReader.AsDataSet(new ExcelDataSetConfiguration()
            {
            ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
                {
                UseHeaderRow = true
                }
            });
 
        // Return as dataset
        DataSet result = excelReader.AsDataSet();
        // Get all tables
        DataTableCollection table = result.Tables;
        // Store in Database
        DataTable resultTable = table["Sheet1"];

Here instead Sheet 1 i Want to Pass SheetName as Parameter(In Existing Code How can i Add // return return resultTable;这里取而代之的是 Sheet 1 我想将 SheetName 作为参数传递(在现有代码中我如何添加//返回返回结果表;

        }

         List<DataCollection> dataCol = new List<DataCollection>();
         public void PopulateInCollection(string fileName)
        {

        DataTable table = ExcelToDatable(fileName);
        for (int row = 1; row <= table.Rows.Count; row++)
            {

            for (int col = 0; col < table.Columns.Count; col++)
                {

                DataCollection dtTable = new DataCollection()
                    {
     


                    rowNumber = row,
                    colName = table.Columns[col].ColumnName,
                    colValue = table.Rows[row - 1][col].ToString()
                    };
                dataCol.Add(dtTable);

                }
            }
        }

        public string ReadData(int rowNumber, string columnName)
        {
        try
            {
            // Retriving data using LINQ to reduce much of iterations
            string data = (from colData in dataCol
                           where colData.colName == columnName && colData.rowNumber == rowNumber
                           select colData.colValue).SingleOrDefault();

            return data.ToString();
            }
        catch (Exception e)
            {
            return null;
            }
        }

        internal class DataCollection
        {
        public int rowNumber { get; internal set; }
        public string colName { get; internal set; }
        public string colValue { get; internal set; }
        }
    }

} }

and the TestClass:和测试类:

        [Test]
        public void DataDrivenTest_FromExcel()
        {

        Driver = new ChromeDriver();
    
        ExcelUtil util = new ExcelUtil();
        util.PopulateInCollection(@"C:\dan\AutomationTest\TestData\test.xlsx");
        Driver.FindElement(By.Id("contentPlaceholder_txtClientCode")) 
       .SendKeys(util.ReadData(i));
    
         Driver.FindElement(By.XPath("//*[@id='btnLogin']")).Click();
         Driver.FindElement(By.XPath("//* 
              [@id='tabContent0']/table/tbody/tr[2]/td[1]")).Click();
        Driver.FindElement(By.Id("contentPlaceholder_txtcloseButton")).Click();
    
          Driver.Quit

           }
List<DataCollection> dataCol = new List<DataCollection>();
public void PopulateInCollection(string fileName, string sheetName)
{
    DataTable table = ExcelToDataTable(fileName, sheetName);
    //Iterate through the rows and columns of the Table
    for (int row = 1; row <= table.Rows.Count; row++)
    {
        for (int col = 0; col <= table.Columns.Count; col++)
        {
            Datacollection dtTable = new Datacollection()
            {
                rowNumber = row,
                colName = table.Columns[col].ColumnName,
                colValue = table.Rows[row - 1][col].ToString()
            };
            //Add all the details for each row
            dataCol.Add(dtTable);
        }
    }
}

public DataTable ExcelToDaTable(string fileName, string sheetName)
{
    // open file and returns as stream

    FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
    // create openXmlReader via ExcelReaderFactory
    IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
    //Set the first row as column name
    var result = excelReader.AsDataSet(new ExcelDataSetConfiguration()
    {
        ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
        {
            UseHeaderRow = true
        }
    });

    // Return as dataset
    DataSet result = excelReader.AsDataSet();
    // Get all tables
    DataTableCollection table = result.Tables;
    // Store in Database
    DataTable resultTable = table[sheetName];
    return resultTable;
}

#End #结尾

//Define this first util.PopulateInCollection("fileName", "sheetName"); //定义第一个 util.PopulateInCollection("fileName", "sheetName");

//Reading from excel file util.ReadData(rowNumber, columnName) //从excel文件中读取 util.ReadData(rowNumber, columnName)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM