Click here to Skip to main content
Click here to Skip to main content

Read Excel File into DataSet in ASP.NET Using C#

, 30 Jul 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
How to read Excel file data into a DataSet in ASP.NET using C#.

Introduction 

In this example, I will explain how to read Excel file data into a DataSet in ASP.NET using C#. I have created an Excel file which contains the Slno, FirstName, LastName, and Location which is shown below:

We would be putting all the data into the grid view and with the help of filter with the dropdown list box, we would filter the Slno and display accordingly, else display all the cell values in the grid.

ASP

<asp:DropDownList ID="ddlSlno" runat="server" 
OnSelectedIndexChanged="ddlSlno_SelectedIndexChanged"
        AutoPostBack="true" AppendDataBoundItems="True">
<asp:ListItem Selected="True" 
Value="Select">- Select -</asp:ListItem>
</asp:DropDownList>
<asp:GridView ID="grvData" runat="server">
</asp:GridView>
<asp:Label ID="lblError" runat="server" />

C# Code

using System;
using System.Data.OleDb;
using System.Data;
using System.IO;
OleDbConnection oledbConn;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GenerateExcelData("Select");
    }
}
 
protected void ddlSlno_SelectedIndexChanged(object sender, EventArgs e)
{
    GenerateExcelData(ddlSlno.SelectedValue);
}
 
private void GenerateExcelData(string SlnoAbbreviation)
{
    try
        {
            // need to pass relative path after deploying on server
            string path = System.IO.Path.GetFullPath(Server.MapPath("~/InformationNew.xlsx"));
            /* connection string  to work with excel file. HDR=Yes - indicates 
               that the first row contains columnnames, not data. HDR=No - indicates 
               the opposite. "IMEX=1;" tells the driver to always read "intermixed" 
               (numbers, dates, strings etc) data columns as text. 
            Note that this option might affect excel sheet write access negative. */

            if (Path.GetExtension(path) == ".xls")
            {
                oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
                Data Source=" + path + ";
                Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
            }
            else if (Path.GetExtension(path) == ".xlsx")
            {
                oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;
                Data Source=" + path + ";
                Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
            }
            oledbConn.Open();
            OleDbCommand cmd = new OleDbCommand(); ;
            OleDbDataAdapter oleda = new OleDbDataAdapter();
            DataSet ds = new DataSet();

            // passing list to drop-down list

            // selecting distinct list of Slno 
            cmd.Connection = oledbConn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT distinct([Slno]) FROM [Sheet1$]";
            oleda = new OleDbDataAdapter(cmd);
            oleda.Fill(ds, "dsSlno");
            ddlSlno.DataSource = ds.Tables["dsSlno"].DefaultView;
            if (!IsPostBack)
            {
                ddlSlno.DataTextField = "Slno";
                ddlSlno.DataValueField = "Slno";
                ddlSlno.DataBind();
            }
            // by default we will show form data for all states 
            // but if any state is selected then show data accordingly
            if (!String.IsNullOrEmpty(SlnoAbbreviation) && SlnoAbbreviation != "Select")
            {
                cmd.CommandText = "SELECT [Slno], [FirstName], [LastName], [Location]" +
                    "  FROM [Sheet1$] where [Slno]= @Slno_Abbreviation";
                cmd.Parameters.AddWithValue("@Slno_Abbreviation", SlnoAbbreviation);
            }
            else
            {
                cmd.CommandText = "SELECT [Slno],
                [FirstName],[LastName],[Location] FROM [Sheet1$]";
            }
            oleda = new OleDbDataAdapter(cmd);
            oleda.Fill(ds);

            // binding form data with grid view
            grvData.DataSource = ds.Tables[1].DefaultView;
            grvData.DataBind();
        }
        // need to catch possible exceptions
        catch (Exception ex)
        {
            lblError.Text = ex.ToString();
        }
        finally
        {
            oledbConn.Close();
        }
}// close of method GemerateExceLData

Result

When you select the value from the dropdown list, the result would be: 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mannava Siva Aditya
Web Developer
India India
I am a 29 year old software Web Developer from Hyderabad, India. I have been working since approximately age 25. Where as in IT Development industry since 27. I am Microsoft Certified Technology Specialist.

I have taught myself in development, beginning with Microsoft's technologies ASP.NET, Approximately 3 years ago, I was given an opportunity to work as a freelance in the tech field. Now I am working as a web developer where my roles make me purely in web based technology solutions which manage and control access to applications and patient information stored in legacy systems, client-server applications.
 
I too had an opportunity to train some IT professionals with technical skills in development area. Which became my passion.
 
I have worked on various .NET framework versions(2.0 , 3.5, 4.0) and have been learning every new technology being introduced. Currently, I am looking forward to working in R & D in .Net to create distributed, reusable applications.
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionAn error occured while running it PinmemberMember 1103284624-Aug-14 7:26 
GeneralNicely done and informative. Thanks. PinmemberSerge-USA28-Jul-14 8:27 
GeneralMy vote of 4 PinmemberAnwar Hossin28-Aug-13 0:33 
GeneralRe: My vote of 4 PinmemberMannava Siva Aditya28-Aug-13 18:06 
GeneralMy vote of 5 Pinmemberraj ch1-Aug-13 0:17 
GeneralRe: My vote of 5 PinmemberMannava Siva Aditya28-Aug-13 18:06 
GeneralMy vote of 1 Pinmemberphilipli31-Jul-13 3:24 
GeneralRe: My vote of 1 PinmemberMannava Siva Aditya31-Jul-13 3:32 
GeneralMy vote of 5 PinmemberFernandoUY30-Jul-13 3:56 
GeneralMy vote of 5 PinmemberJJ Jane24-Jul-13 15:03 
GeneralRe: My vote of 5 PinmemberMannava Siva Aditya24-Jul-13 19:28 
GeneralMy vote of 1 PinmemberFarhan usman6-Jun-13 20:06 
GeneralRe: My vote of 1 PinmemberMannava Siva Aditya15-Jul-13 23:55 
GeneralRe: My vote of 1 PinmemberMannava Siva Aditya24-Jul-13 1:28 
GeneralMy vote of 3 PinprofessionalSingh_Vinay29-May-13 21:39 
GeneralRe: My vote of 3 PinmemberMannava Siva Aditya29-May-13 23:50 
GeneralThanks PinmemberAlireza_136212-May-13 4:54 
GeneralRe: Thanks PinmemberMannava Siva Aditya29-May-13 23:50 
GeneralMy vote of 1 PinmemberJamesPChadwick21-Dec-12 8:39 
Why not make use of the Interop Assemblies for Office?
GeneralRe: My vote of 1 PinmemberMannava Siva Aditya16-Jul-13 0:01 
QuestionWhere do you get the provider? Pinmemberxx_Sandman_xx17-Dec-12 8:28 
AnswerRe: Where do you get the provider? PinmemberMannava Siva Aditya17-Dec-12 17:58 
GeneralRe: Where do you get the provider? Pinmemberxx_Sandman_xx18-Dec-12 10:05 
GeneralMy vote of 5 PinmemberCarsten V2.014-Dec-12 20:40 
GeneralRe: My vote of 5 PinmemberMannava Siva Aditya16-Dec-12 17:27 
GeneralRe: My vote of 5 PinmemberCarsten V2.016-Dec-12 20:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.141015.1 | Last Updated 30 Jul 2013
Article Copyright 2012 by Mannava Siva Aditya
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid