Import excel data to gridview
Simply we have a fileupload control, button control and gridview control in our page. We will use file upload control to upload the excel file and then using its physical path we will get records from it and display them to gridview control.
.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Configuration;
protected void btnImport_Click(object sender, EventArgs e)
{
try
{
string path = uploadExcel.FileName;
uploadExcel.SaveAs(Server.MapPath("~/Upload/" + path));
OleDbConnection oconn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath(path)+";Extended Properties=Excel 8.0");
oconn.Open();
//Getting records from Sheet1 of excel file. As you know one excel file may have many sheets
OleDbCommand ocmd = new OleDbCommand("select * from [Sheet1$]", oconn);
DataSet ds = new DataSet();
OleDbDataAdapter odapt = new OleDbDataAdapter(ocmd);
odapt.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
oconn.Close();
}
catch(Exception exp)
{
throw exp;
}
}
0 comments:
Post a Comment