Reading data from excel in selenium C#

浪尽此生 提交于 2021-02-08 11:15:49

问题


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.


回答1:


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.




回答2:


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.


来源:https://stackoverflow.com/questions/42901883/reading-data-from-excel-in-selenium-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!