Getting Data from excel file to our .net program and filling it into the gridview
Take one FileUpload Control and one Button and GridView
In the codebehind page write the code in Button Click event
protected void Button1_Click(object sender, EventArgs e) { StrName = FileUpload1.PostedFile.FileName;//here we are taking the excel file ex: emp.xls DataTable myData = default(DataTable); myData = GetDataFromExcel(StrName, "Sheet1$").Tables[0]; GridView1.DataSource = myData.DefaultView; GridView1.DataBind(); }
public System.Data.DataSet GetDataFromExcel(string FileName, string RangeName) { try { string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FileName + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\""; //here HDR means Header, if it "Yes" int incluedes Header if it is "No" it will come with out Headers
System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(strConn); objConn.Open();
System.Data.OleDb.OleDbCommand objCmd = new System.Data.OleDb.OleDbCommand("SELECT * FROM [Sheet1$]", objConn); System.Data.OleDb.OleDbDataAdapter objDA = new System.Data.OleDb.OleDbDataAdapter(); objDA.SelectCommand = objCmd;
// Fill DataSet System.Data.DataSet objDS = new System.Data.DataSet(); objDA.Fill(objDS);
objCmd.Connection = objConn; using (OleDbDataReader dr = objCmd.ExecuteReader()) { string sqlConnectionString = "server=SeverName;Initial Catalog=Testing;uid=sa;pwd=**;"; // Bulk Copy to SQL Server using (SqlBulkCopy bc = new SqlBulkCopy(sqlConnectionString)) { bc.DestinationTableName = "emp"; bc.WriteToServer(dr); }
} objConn.Close(); return objDS; } catch { return null; } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|