;

Export Data from datatable to excel in ASP.NET and C#

admin 06:38:pm Jan 29 2017

To export data from a datatable to Excel file 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();
}
}

Related Post

Comments

No comments yet. Be the first!

Add Comment

Adding comments has been disabled.