Paste the Code directly.
/// <Summary>
/// Obtain the Excel file
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Private void button#click (Object sender, eventargs E)
{
Openfiledialog DLG = new openfiledialog ();
DLG. Filter = "Excel file (*. xls) | *. xls ";
If (DLG. showdialog () = dialogresult. OK)
{
String filepath = DLG. filename;
This. textbox1.text = filepath;
}
}
/// <Summary>
/// Import an Excel file
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Private void button2_click (Object sender, eventargs E)
{
If (textbox1.text. Length = 0)
{
MessageBox. Show ("select the Excel file for Data Import ");
}
Else
{
Try
{
Oledbconnectionstringbuilder connectstringbuilder = new oledbconnectionstringbuilder ();
Connectstringbuilder. datasource = This. textbox1.text. Trim ();
Connectstringbuilder. provider = "Microsoft. Jet. oledb.4.0 ";
Connectstringbuilder. Add ("extended properties", "Excel 8.0 ");
Using (oledbconnection Cn = new oledbconnection (connectstringbuilder. connectionstring ))
{
Dataset DS = new dataset ();
String SQL = "select * from [sheet1 $]";
Oledbcommand refreshing liming = new oledbcommand (SQL, CN );
CN. open ();
Using (oledbdatareader drliming = logging liming. executereader ())
{
DS. Load (drliming, loadoption. overwritechanges, new string [] {"sheet1 "});
Datatable dt = Ds. Tables ["sheet1"];
If (Dt. Rows. Count> 0)
{
For (INT I = 0; I <DT. Rows. Count; I ++)
{
// Write database data
String MySQL = "insert into clientinfo values ('" + dt. rows [I] ["name"]. tostring () + "','" + dt. rows [I] ["name"]. tostring ()
+ "', '0','" + dt. rows [I] ["Remarks"]. tostring () + "', '0','" + I. tostring () + "')";
New dataaccess (). sqlexecute (MySQL );
}
MessageBox. Show ("data import successful! ");
}
Else
{
MessageBox. Show ("check whether data exists in your Excel ");
}
}
}
}
Catch (exception ex)
{
MessageBox. Show (ex. tostring ());
}
}
}
/// <Summary>
/// Common data operation class
/// </Summary>
/// <Param name = "SQL"> </param>
/// <Returns> </returns>
Public bool sqlexecute (string SQL)
{
Try
{
Oledbconnection conn = new oledbconnection (connect_string );
Conn. open ();
Oledbcommand comm = new oledbcommand ();
Comm. Connection = conn;
Comm. commandtext = SQL;
Comm. executenonquery ();
Comm. Connection. Close ();
Conn. Close ();
Return true;
}
Catch
{
Return false;
}
}