2014-12-08 35 views
0

我想從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」。

我知道它一直工作到選擇語句。有人可以幫助我我基本上只是想能夠訪問我在選擇聲明中獲得的信息。

回答

1

您需要一個OleDBDataAdapter而不是SqlDataAdapter。那麼,這樣做:

OleDBDataAdapter da = new OleDBDataAdapter(cmdExcel); 
da.Fill(dataset); 

Excel是一個OLEDB數據源,所以你應該使用將與一般OleDb爲前綴的類,就像那些用於數據庫連接和操作與Sql前綴。

Documentation

+0

是啊,這是有道理給出的錯誤 – Danrex 2014-12-08 08:13:56

2

訪問使用OLEDB連接Excel數據始終是一個headache.You可以嘗試第三方控件,而不是像Aspose。用法很簡單。你可以添加控件的引用到項目後,試試下面的代碼。

//Creating a file stream containing the Excel file to be opened 
FileStream fstream = new FileStream("C:\\book1.xls", FileMode.Open); 

//Instantiating a Workbook object 
//Opening the Excel file through the file stream 
Workbook workbook = new Workbook(fstream); 

//Accessing the first worksheet in the Excel file 
Worksheet worksheet = workbook.Worksheets[0]; 

//Exporting the contents of 7 rows and 2 columns starting from 1st cell to DataTable 
DataTable dataTable = worksheet.Cells.ExportDataTable(0, 0, 7, 2, true); 

//Binding the DataTable with DataGrid 
dataGrid1.DataSource = dataTable; 

//Closing the file stream to free all resources 
fstream.Close(); 
+0

我會嘗試這種謝謝。 – Danrex 2014-12-08 08:14:51