我想从C#中的Excel中访问数据。理想情况下,我想将数据放入列表或一系列集合中。我正在使用本教程 - http://www.aspsnippets.com/Articles/Read-Excel-file-using-OLEDB-Data-Provider-in-C-Net.aspx。如何访问C#中的Excel数据
这非常有帮助,但我认为他错过了数据适配器部分。这是我遵循他的例子得到的代码。
string connectionString = null;
connectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = P:\\Visual Studio 2012\\Projects\\SmartSheetAPI\\SmartSheetAPI\\bin\\Debug\\OUTPUT.xls; Extended Properties = 'excel 12.0 Xml; HDR=YES; IMEX=1;';";
//Establish Connection
string dataSource = "P:\\Visual Studio 2012\\Projects\\SmartSheetAPI\\SmartSheetAPI\\bin\\Debug\\OUTPUT.xls;";
string excelConnection = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source = " + dataSource + " Extended Properties='Excel 8.0; HDR=Yes'";
OleDbConnection connExcel = new OleDbConnection(connectionString);
OleDbCommand cmdExcel = new OleDbCommand();
cmdExcel.Connection = connExcel;
//Accessing Sheets
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
connExcel.Close();
//access excel Sheets (tables in database)
DataSet dataset = new DataSet();
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
da.SelectCommand = cmdExcel;
da.Fill(dataset);
connExcel.Close();
如果你看下面三行,你会注意到他使用da.SelectCommand和da.Fill来填充数据集。但我认为这需要一个数据适配器,而他没有这个例子。我曾尝试创建如下一个DataAdapter:
SqlDataAdapter dataadapter = new SqlDataAdapter();
,但我得到一个错误,说明:可以键入“System.Data.OleDb.OleDbCommand”不能隐式转换为System.Data.SqlClient.SqlCommand”。
我知道它一直工作到选择语句。有人可以帮助我我基本上只是想能够访问我在选择声明中获得的信息。
是啊,这是有道理给出的错误 – Danrex 2014-12-08 08:13:56