![](/img/trans.png)
[英]How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries
[英]How to read an Excel data file through Selenium without Interop and Microsoft Excel installed in the Local machine in C#?
我正在嘗試使用 Microsoft Visual Studio 中的 Selenium C# 綁定來獲得數據驅動的自動化解決方案。 我的挑戰是在沒有 Excel 應用程序的情況下從 Excel 讀取,最好使用 Closed XML 或 OLEDB 連接。 有什么幫助或想法嗎?
[21:28] 以利沙,席巴
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;
}
我得到的數據不是格式錯誤。
考慮使用ExcelDataReader 。 以下讀取所有工作表並包括可選的列標題。
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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.