Хотите читать данные из разных листов Excel в одном файле Excel, используя selenium c# - PullRequest
0 голосов
/ 20 апреля 2020

Использовали пакет ExcelDataReader NuGET.

Это класс, устанавливающий его -

    private static DataTable ExcelToDataTable(string fileName)
    {
        //open file and returns as Stream
        FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
        //Createopenxmlreader via ExcelReaderFactory
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //.xlsx
                                                                                       //Set the First Row as Column Name
        excelReader.IsFirstRowAsColumnNames = true;
        //Return as DataSet
        DataSet result = excelReader.AsDataSet();
        //Get all the Tables
        DataTableCollection table = result.Tables;
        //Store it in DataTable
        DataTable resultTable = table["Sheet1"];
        //return
        return resultTable;
    }
   static List<Datacollection> dataCol = new List<Datacollection>();

public static void PopulateInCollection(string fileName)
    {
        DataTable table = ExcelToDataTable(fileName);

        //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 static 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();

            //var datas = dataCol.Where(x => x.colName == columnName && x.rowNumber == rowNumber).SingleOrDefault().colValue;
            return data.ToString();
        }
        catch (Exception)
        {
            return null;
        }
    }


}

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

}


Вызывается в коде как -

   //setting the excel file location
ExcelLib.PopulateInCollection(@"C:\Users\User1\Documents\data.xlsx");
//reading data from row 1 & column named middlename
xrmApp.Entity.SetValue("middlename", ExcelLib.ReadData(1, "middlename"));

Я хочу иметь возможность использовать этот код в разных методах, и для каждого метода мне нужны разные данные. Так или иначе, я могу добавить параметр номера листа в код, чтобы я мог указать, какой лист просматривать при чтении номера строки и номера столбца.

Спасибо!

1 Ответ

0 голосов
/ 28 апреля 2020

Исходя из вашего описания, вы хотите прочитать данные из другого листа в одном файле

.

Я предлагаю вам преобразовать файл Excel в набор данных и выбрать набор данных из набора данных

.

Как и в следующем коде:

Перед этим, пожалуйста, установите пакет nuget ExcelDataReader и ExcelDataReader.DataSet.

 class Program
 {
    static void Main(string[] args)
    {
        DataSet set = ExcelToDataSet("D:\\test.xlsx");
        DataTable table = set.Tables[0];   // first sheet
        string data = ReadData(table, 0, "TeacherName");// the first row and colunname is teachername
        Console.WriteLine(data);
        table = set.Tables[1];             //second sheet
        data = ReadData(table, 0, "StuName");// the first row and colunname is stuname
        Console.WriteLine(data);
        Console.ReadKey();

    }

    private static DataSet ExcelToDataSet(string fileName)
    {
        //open file and returns as Stream
        FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
        //Createopenxmlreader via ExcelReaderFactory
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //.xlsx
                                                                                       //Set the First Row as Column Name
        DataSet result = excelReader.AsDataSet(new ExcelDataSetConfiguration()
        {
            ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
            {
                UseHeaderRow = true
            }
        });
        //Get all the Tables
        //return
        return result;
    }

    static string ReadData(DataTable table,int row,string columnname)
    {
        return table.Rows[row].Field<string>(columnname).ToString();
    }


}

Я создал следующий Excel:

Первый лист:

enter image description here

Второй лист:

enter image description here

Если я запусту приведенный выше код, вы получите значение первого ряда и первого столбца двух листов. enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...