简体   繁体   中英

Reading data from excel in selenium C#

I'm trying to read username and password from excel sheet while using Selenium in C# .NET. Below is the code:

using excel = Microsoft.Office.Interop.Excel;

public void TestMethod1()
{
       excel.Application xlApp = new excel.Application();
       excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:\Test\TestData.xlsx");
       excel._Worksheet xlWorksheet = **xlWorkbook.Sheets[1];**
       excel.Range xlRange = xlWorksheet.UsedRange;
 }

I'm getting the following error at the text that is marked in bold in above code:

Error CS0656 Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.Binder.Convert' Read Data From Excel_Office c:\\users\\tabish.khan\\documents\\visual studio 2015\\Projects\\Read Data From Excel_Office\\Read Data From Excel_Office\\OfficeReadExcel.cs 18 Active

Please help me resolve this issue.

I have the same error with my C# Class Library project. I'm using .NET Framework 4.6 and I used NuGet to install the Microsoft.Office.Interop.Excel assembly:

PM> Install-Package Microsoft.Office.Interop.Excel

Here is a simplified version of the code which causes this error:

using MSExcel = Microsoft.Office.Interop.Excel;

namespace ProjectReader
{
    public class ExcelExport
    {

        public ExcelExport()
        {
            xlApp = new MSExcel.Application();
            xlWorkBook = xlApp.Workbooks.Add(System.Reflection.Missing.Value);
        }

        public void CreateFile()
        {
            object missingValue = System.Reflection.Missing.Value;

            foreach (MSExcel.Worksheet sht in xlWorkBook.Sheets)
            {
                if (xlWorkBook.Worksheets.Count > 1)
                {
                    sht.Delete();
                }
            }

            **xlWorkSheet = (MSExcel.Worksheet)xlWorkBook.Sheets[1];**
        }

        private MSExcel.Application xlApp;
        private MSExcel.Workbook xlWorkBook;
        private MSExcel.Worksheet xlWorkSheet;
    }
}

Interestingly, I have no issues referencing the worksheets in the foreach loop just above the offending line.

Use the following steps:-

  1. Go to your project and right click.
  2. Click on Add then click on Reference..
  3. Select Microsoft.CSharp and click on OK button then clean and rebuild your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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