Import Excel in ASP.NET using FileUpload control

 

We can upload the Microsoft Excel file by using FileUpload control to the database or we can display by using Gridview control.

To read the data from Excel file we have to use System.Data.OleDb namespace.  By using Microsoft.Jet.OLEDB.4.0 we can read the data from Excel sheet as shown below.

Default.aspx 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ReadExcelAspNet.WebForm1" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml"> 

<head runat="server"> 

    <title></title> 

</head> 

<body> 

    <form id="form1" runat="server"> 

    <div> 

        <asp:FileUpload ID="fu1" runat="server" />

 

        <asp:Button ID="btnLoad" Text="Load To Grid" runat="server" OnClick="btnLoad_Click" /><br />

 

        <asp:GridView ID="gv1" runat="server"></asp:GridView> 

    </div> 

    </form> 

</body> 

</html>

 

Default.aspx.cs 

using System; 

using System.Data; 

using System.Data.OleDb;

 

namespace ReadExcelAspNet 

{ 

    public partial class WebForm1 : System.Web.UI.Page 

    { 

        protected void Page_Load(object sender, EventArgs e) 

        {

 

        }

 

        protected void btnLoad_Click(object sender, EventArgs e) 

        { 

            try 

            { 

                string sFilePath = System.IO.Path.GetFullPath(fu1.PostedFile.FileName); 

                string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; data source=" + sFilePath + "; Extended Properties=Excel 8.0;";

 

                OleDbDataAdapter odad = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString); 

                DataSet ds = new DataSet();

 

                odad.Fill(ds);

 

                gv1.DataSource = ds.Tables[0]; 

                gv1.DataBind(); 

            } 

            catch (Exception ex) 

            {

 

            } 

        } 

    } 

}

 

As shown above we are reading the data from Microsoft Excel sheet Sheet1 and displaying the data by using Gridview.

                                                                                                                  ReadExcelAspNet.zip (23.94 kb)