Thursday, November 24, 2011

Show excel sheet data in Gridview using C#

Hi All,
   This post show how you can show data of Microsoft Excel Sheet inside a ASP.NET gridview.

The excel sheet in this example is generated by exporting the Northwind Database's Customers table . I have placed the excel sheet  in my D:\ directory and named it as "Test".

The excel sheet looks something like this :





Now on a web page take a ASP.NET GridView Control and and on the Page_load event write this code :


        string F1Name = "D:\\Test.xls";
        string CnStr = ("Provider=Microsoft.Jet.OLEDB.4.0;" + ("Data Source="
        + (F1Name + (";" + "Extended Properties=\"Excel 8.0;\""))));
        DataTable DT = new DataTable();
        OleDbDataAdapter DA = new OleDbDataAdapter("Select * from [Customers$]", CnStr);
       Response.Write("File Accessed!!!!");
        try
        {
            DA.Fill(DT);
            GridView1.DataSource = DT;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
                      

Run the WebPage and see the result as: 







Hope it will be useful.

Thanks,
Nitin Sharma