Monday, 15 August 2011

Import Data From Excel Into Gridview

In this tutorial you will learn how to import data from excel into gridview in asp.net. you can easily use this code in your page and can get desired functionality.

/*Here is the aspx code in which you have asp.net file uploader and a button to perform import functionality.*/


























/* If your code is placed on server then first you need to save file in a folder and then get record from that file.*/

protected void btnImport_Click(object sender, EventArgs e)
{
string path = uploadExel.FileName;
uploadExel.SaveAs(Server.MapPath("~/Folder Name/" + path));// Save file on server

//if using office 2003 or lower then use below connection string

string connString=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath(path)+";Extended Properties=Excel 8.0";

//if using office 2007 or later then use below connection string
string connString=@" Provider=Microsoft.ACE.OLEDB.12.0;
Data Source="+Server.MapPath(path)+";Extended Properties=Excel 8.0";
OleDbConnection conn = new OleDbConnection(connString);  

oconn.Open();                        
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", conn);
/* Here sheet1 is the name of sheet in from where you have data.*/
DataSet ds = new DataSet();
OleDbDataAdapter dapt = new OleDbDataAdapter(cmd);
dapt.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
oconn.Close();            
}

No comments:

Post a Comment