Wednesday 20 February 2013

How to export DataTable into Excel file in ASP.NET

There is a one simple function written below, which takes datatable as a parameter and give it popup to user to save the file as an excel file.
Copy and paste file in your code, and call this function on Event where it required

using System;
using System.Data;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI;
protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Qualification", typeof(string));
        dt.Rows.Add("Raja", "M.B.A");
        dt.Rows.Add("Durai", "M.B.B.S");
        dt.Rows.Add("SRD", "BE");
        ExportToExcel(dt);
    }

public void ExportToExcel(DataTable dt)
    {
        if (dt.Rows.Count > 0)
        {
            string filename = "Raja.xls";
            string excelHeader = "Raja Report";
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            DataGrid dgGrid = new DataGrid();
            dgGrid.DataSource = dt;
            dgGrid.DataBind();
            // Report Header
            hw.WriteLine("<b><u><font size='3'> " + excelHeader + " </font></u></b>");
            //Get the HTML for the control.
            dgGrid.RenderControl(hw);
            //Write the HTML back to the browser.          
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
            this.EnableViewState = false;
            Response.Write(tw.ToString());
            Response.End();
        }
    }

 

No comments:

Post a Comment