Import Excel Data to gridiew in Asp.net

Source: Internet
Author: User

 

Code
Protected   Void Button#click ( Object Sender, eventargs E)
{
If (Myfile. postedfile. filename ! =   "" )
{
// Absolute path of the uploaded file
String Sfile = Myfile. postedfile. filename;
// Get file full name
Sfile = Sfile. substring (sfile. lastindexof ( " \\ " ) +   1 );
// Get suffix
Sfile = Sfile. substring (sfile. lastindexof ( " . " ));
If (Sfile. tolower () ! =   " . Xls " )
{
Response. Write ( " Select an Excel file! " );
Response. End ();
}
// To prevent duplicate names, obtain the date as the file name year month day hour minute second millisecond
String Datatime = System. datetime. Now. tostring ( " Yyymmddhhmmssffff " );
// New name of the uploaded file
Sfile = Datatime + Sfile;
// Appdomain. currentdomain. basedirectory. tostring () Get the root directory of this project
// Upload files
Myfile. saveas (server. mappath ( " . " ) +   " \\ "   + Sfile );
Dataset DS = Getexcelcontent (server. mappath ( " . " ) +   " \\ "   + Sfile );
This . Mygridview. datasource = DS;
This . Mygridview. databind ();
}
}
// Read EXCEL to DatasetCode:
Public Dataset getexcelcontent ( String Filepath)
{
String Strcon =   " Provider = Microsoft. Jet. oledb.4.0; Data Source = "   + Filepath +   " ; Extended properties = 'excel 8.0; HDR = no; IMEX = 1' " ;
Oledbconnection myconn =   New Oledbconnection (strcon );
String Strcom =   " Select * from [sheet1 $] " ;
Myconn. open ();
Oledbdataadapter mycommand =   New Oledbdataadapter (strcom, myconn );
// Create a DataSet object
Dataset mydataset =   New Dataset ();
// Get your DataSet object
Mycommand. Fill (mydataset );
// Close this data link
Myconn. Close ();
Return Mydataset;
}

 

In this way, the data is imported into the dataset.

Importing data from dataset to the database seems like a good operation.

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.