Create a data source Connection string for the Connection object:
"Provider = Microsoft. Jet. Oledb.4.0; Data Source = Excel file physical path +"; Extended Properties = Excel 8.0 ";
The SQL statement in the DataAdapter object should be: "Select field list From [worksheet name $]"
Example:
<% @ Import NameSpace = "System. Data" %>
<% @ Import NameSpace = "System. Data. OleDb" %>
<Script Language = "C #" runat = "server">
Void Page_Load (Object sender, EventArgs e)
{
String strConn = "Provider = Microsoft. Jet. Oledb.4.0; Data Source =" + Server. MapPath ("Book1.xls") + "; Extended Properties = Excel 8.0 ";
OleDbConnection conn = new OleDbConnection (strConn );
OleDbDataAdapter adp = new OleDbDataAdapter ("Select * from [Sheet1 $]", conn );
DataSet ds = new DataSet ();
Adp. Fill (ds, "Book1 ");
ExlDataGrid. DataSource = ds. Tables ["Book1"]. DefaultView;
ExlDataGrid. DataBind ();
}
</Script>
<Html>
<Body>
<H4 align = "center"> reading Excel files <Asp: DataGrid id = "ExlDataGrid" width = "100%" HeaderStyle-BackColor = "#999999" ForeColor = "#333333" runat = "server"> </asp: DataGrid>
</Body>
</Html>
I want to provide you with a program that I used to import excel files to the SQL database yesterday. It is the button1 button that starts to import data. The excel file is the third colum .. as follows:
Private void button#click (object sender, System. EventArgs e)
{
String mystring = "Provider = Microsoft. Jet. OLEDB.4.0; Data Source = 'd:/ExportToExcel/excel/test.xls '; Extended Properties = Excel 8.0 ";
OleDbConnection cnnxls = new OleDbConnection (mystring );
OleDbDataAdapter myDa = new OleDbDataAdapter ("select * from [Sheet1 $]", cnnxls );
DataSet myDs = new DataSet ();
MyDa. Fill (myDs );
If (myDs. Tables [0]. Rows. Count> 0)
{
String strSql = "";
String CnnString = "Provider = SQLOLEDB; database = testnews; server = (local); uid = sa; pwd = ";
OleDbConnection conn = new OleDbConnection (CnnString );
Conn. Open ();
OleDbCommand myCmd = null;
For (int I = 0; I <myDs. Tables [0]. Rows. Count; I ++)
{
StrSql = "insert into news (title, body) values ('";
StrSql + = myDs. Tables [0]. Rows [I]. ItemArray [1]. ToString () + "','";
StrSql + = myDs. Tables [0]. Rows [I]. ItemArray [2]. ToString () + "')";
Try
{
MyCmd = new OleDbCommand (strSql, conn );
MyCmd. ExecuteNonQuery ();
Label8.Text = "<script language = javascript> alert ('data imported successfully. '); </script> ";
}
Catch
{
Label8.Text = "<script language = javascript> alert ('data import failed. '); </script> ";
}
}
Conn. Close ();
}
}
}