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

Viewed 459

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. I only need to read Data From SheetName, right now i have Contstant SheetName (i,e sheet1), wanted to add SheetName Parameter

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

My Excel Generic Code is Below:

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

        }

         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

           }
1 Answers
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");

//Reading from excel file util.ReadData(rowNumber, columnName)

Related