Reference: How to read from an Excel file using OLE DB
For ease of use, I made the tool class (OledbHelp.cs), good for later use.
Note: In the connection string, Provider=xx is modeled from this connection, mainly considering whether to treat line 1th as a table header: http://www.connectionstrings.com/excel/
Code for the OledbHelp.cs class:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Data.OleDb;6 usingSystem.Data;7 usingSystem.Collections;8 9 namespaceOLE DB {Ten classOledbhelp { One Public stringFileName {Get;Private Set; } A Private stringConnectString =NULL; - - /// <summary> the ///if contains header. - /// </summary> - ReadOnly BOOLHasheader =false; - Public BOOLHasheader {Get{returnHasheader;} } + - /// <summary> + ///Initialize connection string. A /// </summary> at /// <param name= "FileName" >Full file name.</param> - /// <param name= "Hasheader" >ture if the. xls file contains header;otherwise false.</param> - PublicOledbhelp (stringFileName,BOOLHasheader) { - if(string. IsNullOrEmpty (FileName))Throw NewArgumentNullException ("FileName"); -FileName =FileName; - This. Hasheader =Hasheader; inConnectString ="provider=microsoft.ace.oledb.12.0;data source= '"+ FileName +"';"; - to //specify it contains header. + if(Hasheader) -ConnectString + ="Extended properties= ' Excel 12.0 Xml; Hdr=yes '"; the } * $ PublicOleDbConnection getconnection () {Panax Notoginseng return NewSystem.Data.OleDb.OleDbConnection (connectstring); - } the + PublicDataSet GetDataSet (stringsql, OleDbConnection connection) { AOleDbDataAdapter adapter =NewOleDbDataAdapter (SQL, connection); theDataSetSet=NewDataSet (); +Adapter. Fill (Set); - return Set; $ } $ - /// <summary> - ///Get DataRows by specified column-name. the /// </summary> - /// <param name= "Set" >The input set.</param>Wuyi /// <param name= "ColumnName" >The specified Column-name</param> the /// <returns></returns> - PublicList<datarow> Getdatarow (DataSetSet,stringcolumnName) { WuDataTable T =Set. tables[0];//get the first table as default. -list<datarow> rows =NewList<datarow>(); About foreach(DataRow Rincht.rows) { $ rows. ADD (DataRow) r[columnname]); - }; - returnrows; - } A } +}
Main calling code:
1 stringFileName =@"D:\cs\office\excel\excel_data\tmp.xls";2 stringsql ="SELECT [Name] from [msg$]";//You can specify column fields in SQL statements.3Oledbhelp OLE =NewOledbhelp (FileName,true);4 using(OleDbConnection conn =OLE. Getconnection ()) {5DataSetSet=OLE. GetDataSet (SQL, conn);6DGV. DataSource =Set. tables[0];7}
The effect of running:
Use OLE DB to read Excel (without an Excel object).