Export data from datatable to Excel in ASP.Net,C#



To Export the data from a datatable to Excel in ASP.net using C# use the following code:-  


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;

public void ExportToExcel(DataTable dt, string reportName)
{
        StringBuilder sbTop = new StringBuilder();
        sbTop.Append("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" ");        
        sbTop.Append("<![endif]--> <style type='text/css'>.y{ background-color:Red;border:solid thin black; } .n{ border:solid thin black; } .b{ border:solid thin black;font-weight:bold; } </head><body>");
        
        sbTop.Append("<table>");
        string bottom = "</table></body></html>";
        
        StringBuilder sb = new StringBuilder();

        //Header
        sb.Append("<tr>");
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            sb.Append("<td class=b>" + dt.Columns[i].ColumnName + "</td>");
        }
        sb.Append("</tr>");

        //Items
        for (int x = 0; x < dt.Rows.Count; x++)
        {
            sb.Append("<tr>");
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                sb.Append(@"<td class=n>" + dt.Rows[x][i] + "");                
            }
            sb.Append("</tr>");
        }

        HttpContext.Current.Response.AppendHeader("Content-Type", "application/vnd.ms-excel");
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + reportName + "");
        string srtr = sbTop.ToString() + sb.ToString() + bottom;

        HttpContext.Current.Response.Write(srtr);
        HttpContext.Current.Response.End();
    }
}

Comments

Post a Comment