infolink

Monday 27 May 2013

Export data to Excel in ASP.NET


Today we learn how export the data from the database into Microsoft excel sheet.  So many techniques or ways to export the data into Microsoft excel sheet, but here I have tried to use the easiest way for this purpose or task. No extra namespace, class our assemblies are not required for it. Just follow few steps and get the data on the excel sheet.

We will work step by step

  • First step is to create the database and insert the values in it.
  • Now add the Dataset into the project. And create a query in it that gets the data from the database table.
  • Now go to the .CS page and write the code for it.
Bellow is step by step Example for this task.

Step 1:

Right click on project and add the Dataset.

Export data to Excel in ASP.NET
Export data to Excel in ASP.NET

Export data to Excel in ASP.NET
Export data to Excel in ASP.NET

 Step 2:

From the server explorer drag a table from the database and drop it into the Dataset. Like this.

Export data to Excel in ASP.NET
Export data to Excel in ASP.NET

 Step 3:

Open .aspx page. Here I am use “Default.aspx”. On page add a button. When button press the export process will run. So now on the button click event write the following cod.

Code:
protected void Button1_Click(object sender, EventArgs e)
        {
            DataSet1TableAdapters.CustomerTableAdapter object_customer = new       DataSet1TableAdapters.CustomerTableAdapter();
            DataSet1.CustomerDataTable table = object_customer.GetData();
            DataGrid dg = new DataGrid();
            dg.DataSource = table;
            dg.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename= CustomerReport.xls");
            Response.ContentType = "application/excel";
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            dg.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }

Step 4:

After the code save the file and run the page. And click or press the button. File Download window will open, save the Excel file and check the excel file data will show in it.
Export data to Excel in ASP.NET
Export data to Excel in ASP.NET

Here is the output:

Export data to Excel in ASP.NET
Export data to Excel in ASP.NET

I hope this tutorial will helpful for you. Now follow these simple and easy steps and achieve you target. 
Best Regard.


No comments:

Post a Comment