简体   繁体   中英

How to read an Excel data file through Selenium without Interop and Microsoft Excel installed in the Local machine in C#?

I am trying to work on a solution to get data driven automation using Selenium C# binding in Microsoft Visual Studio. My challenge is to read from Excel without Excel application preferably using Closed XML or OLEDB connections. Any help or thought?

[21:28] Elizha, Sheeba

private DataSet GetExcelDataSet(string path) 
{ 
    string sheetName; 
    string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + "; Jet OLEDB:Engine Type = 5; Extended Properties =\"Excel 8.0;\""; 
    DataSet ds = new DataSet(); 

    using (OleDbConnection con = new OleDbConnection(ConnectionString)) 
    { 
        using (OleDbCommand cmd = new OleDbCommand()) 
        { 
            using (OleDbDataAdapter oda = new OleDbDataAdapter()) 
            { 
                cmd.Connection = con; 
                con.Open(); 
 
                DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 

                for (int i = 0; i < dtExcelSchema.Rows.Count; i++) 
                { 
                    sheetName = dtExcelSchema.Rows[i]["TABLE_NAME"].ToString();
                    DataTable dt = new DataTable(sheetName); 

                    cmd.Connection = con; 
                    cmd.CommandText = "SELECT * FROM [" + sheetName + "]"; 
                    oda.SelectCommand = cmd; 
                    oda.Fill(dt); 
                    dt.TableName = sheetName; 

                    ds.Tables.Add(dt); 
                } 
            } 
        } 
    } 

    return ds; 
}

Am getting data not in the format error.

Consider using ExcelDataReader . The following reads all WorkSheets and includes column headers which is optional.

public static DataSet GetSheets(string excelFileName)
{
    using (var stream = File.Open(excelFileName, FileMode.Open, FileAccess.Read))
    {
        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            var dataSet = reader.AsDataSet(new ExcelDataSetConfiguration()
            {
                UseColumnDataType = true,
                ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                {
                    UseHeaderRow = true
                }
            });

            return dataSet;
        }
    }
}

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