Как получить путь к проекту Excel - PullRequest
0 голосов
/ 09 марта 2020

В моем проекте у меня есть папка Test Data, и внутри нее у меня есть файл xlsx.

enter image description here

Я пытаюсь получить папку пути проекта, чтобы она читала их вместо жесткого кодирования пути. Но он всегда идет и читает форму проекта / bin / debug path. Вот моя утилита Excel. В моем классе я инициализирую класс ExcelUtil и использую метод ReadData

    public class ExcelUtil
    {
        public static void InitializeExcel()
        {
            string exeDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            File.OpenRead(System.IO.Path.Combine(exeDir, "Data.xlsx"));


        }

        public static DataTable ExcelToDataTable(string fileName)
        {
            //Open the file
            using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
            {
                //read the excel file
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    var result = reader.AsDataSet(new ExcelDataSetConfiguration()
                    {
                        //using anaysome method
                        ConfigureDataTable = (data) => new ExcelDataTableConfiguration()
                        {
                            UseHeaderRow = true
                        }
                    });

                    //Storing in DataCollection
                    DataTableCollection table = result.Tables;
                    DataTable resultTable = table["Sheet1"];
                    return resultTable;
                }
            }
        }

        //storing the Data from excel in List type of othe custom class
        public static List<DataCollection> datacol = new List<DataCollection>();

        //Method populates the data into the collection
        public static void PopulateInCollection(string fileName)
        {
            DataTable table = ExcelToDataTable(fileName);

            //Iterating through the rows and columns
            for (int row = 1; row <= table.Rows.Count; row++)
            {
                for (int col = 0; col < table.Columns.Count; col++)
                {
                    DataCollection dTable = 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(dTable);
                }
            }
        }

        //Method read data from excel using rownum and colname
        public static string ReadData(int rowNumber, string columnName)
        {
            try
            {
                //Retriving data using LINQO to reduce much iterations
                string data = (from colData in datacol
                               where colData.ColName == columnName && colData.RowNumber == rowNumber
                               select colData.ColValue).SingleOrDefault();

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

    //Custom class to hold rowsnum and columnnum adn val data
    public class DataCollection
    {
        public int RowNumber { get; set; }
        public string ColName { get; set; }
        public string ColValue { get; set; }
    }
}

1 Ответ

0 голосов
/ 10 марта 2020

Поскольку вы используете NUnit, вам нужно получить путь от TestContext.CurrentContext.TestDirectory, который будет папкой, из которой выполняются тесты. Затем просто добавьте свой относительный путь к этому:

public static void InitializeExcel()
{
    string testDataPath = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "TestData");
    File.OpenRead(System.IO.Path.Combine(testDataPath, "Data.xlsx"));
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...