C # import data functions from an Excel table to Dataset

Source: Internet
Author: User
/// <Summary>
/// Method 3 for reading data from an Excel table, return the dataset Dataset
/// </Summary>
/// <Param name = "str"> address of the file to be opened </param>
/// <Returns> </returns>
Private dataset getexceldataset1 (string strexcelfilepath)
{
Try
{
/// Establish a connection to read data in the table
String strcon = "provider = Microsoft. jet. oledb.4.0; Data Source = "+ strexcelfilepath +"; extended properties = 'excel 8.0; HDR = yes; IMEX = 1'; "; // create a connection, the address passed by Str
Oledbconnection myconn = new oledbconnection (strcon );
String strcom = "select * from [sheet1 $ A: q]"; // SQL statement, that is, to obtain all data from sheet1
Myconn. open ();
Oledbdataadapter mycommand = new oledbdataadapter (strcom, myconn );
Dataset mydataset = new dataset (); // create a new dataset mydataset
Mycommand. Fill (mydataset, "[sheet1 $]"); // fill the dataset
Myconn. Close ();
Int columnnum = mydataset. Tables [0]. Columns. Count; // read the number of columns and assign the value to columnnum
Int rownum = mydataset. Tables [0]. Rows. Count; // read the number of rows and assign the value to rownum
Int resultrownum = columnnum-1;
Console. writeline ("columns" + columnnum. tostring ());
Console. writeline ("number of rows" + rownum. tostring ());
Console. writeline ("Number of valid records" + resultrownum. tostring ());
/// Number of rows to read the result (in fact, the number column in the first column is removed, and the result is displayed in a horizontal position in my program)

Return mydataset;
}
Catch (exception ex)
{
MessageBox. Show ("error occurred" + ex. Message );
Return NULL;
}
}
Related Article

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.