中从Excel读取数据

中从Excel读取数据

本文介绍了在Selenium C#中从Excel读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在C#.NET中使用Selenium时从excel工作表中读取用户名和密码.下面是代码:

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:

请帮助我解决此问题.

推荐答案

我的C#类库项目有相同的错误.我正在使用.NET Framework 4.6,并使用NuGet安装了Microsoft.Office.Interop.Excel程序集:

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

有趣的是,我在问题行上方的foreach循环中引用工作表没有问题.

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

这篇关于在Selenium C#中从Excel读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 22:57