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.