Use oledb to import EXCEL to Dataset

Source: Internet
Author: User

In this method, all the sheet data in the input Excel file is filled in the dataset. This is a simple and quick method. The disadvantage is that it is not suitable for complicated Excel files.

Using System. Data;
Using System. Data. oledb;
Using System. Data. ODBC;

Public Dataset getdatasetfromexcel ( String Filepath)
{
String Strconn =   " Provider = Microsoft. Jet. oledb.4.0; " ;
Strconn + =   " Data Source = "   + Filepath +   " ; " ;
Strconn + =   " Extended properties = Microsoft Excel 8.0; " ;
// Strconn + = "HDR = yes; IMEX = 1 ";

Oledbconnection objconn =   New Oledbconnection (strconn );

Arraylist sheetnamelist =   New Arraylist ();

Try
{
Objconn. open ();

Datatable dtexcelschema = Objconn. getoledbschematable (oledbschemaguid. Tables, New   Object [] {Null,Null,Null,"Table"} );

String Sheetname = "" ;

For ( Int I = 0 ; I < Dtexcelschema. Rows. Count; I ++ )
{
Sheetname=Dtexcelschema. Rows [I] ["Table_name"]. Tostring ();
Sheetnamelist. Add (sheetname );
}
}
Catch (Exception ex)
{
ThrowEx;
}
Finally
{
Objconn. Close ();
}  

Dataset dsexcel =   New Dataset ();

Try
{
String Strsql =   "" ;

For ( Int I = 0 ; I < Sheetnamelist. Count; I ++ )
{
// String strsql = "select * from [sheet1 $ E5: G23]";
// String strsql = "select [F1], [F2], [F3] from [sheet2 $:100]";
Strsql =   " Select * from [ "   + ( String ) Sheetnamelist [I] +   " ] " ;
Oledbdataadapter oleexceldataadapter =   New Oledbdataadapter (strsql, objconn );
Datatable dtexcel =   New Datatable (( String ) Sheetnamelist [I]);
Oleexceldataadapter. Fill (dtexcel );
Dsexcel. Tables. Add (dtexcel );
}
Return Dsexcel;
}
Catch (Exception ex)
{
ThrowEx;
}
}

Reprinted from: http://blog.csdn.net/fangxinggood/archive/2005/06/18/397315.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.