Export to excel in ASP.NET using C#

Export to excel in ASP.NET using C#

In this article we are going to show two examples of exporting to excel. First one is how to export grid view control to excel and the second one is how to export data table to excel.

1-Export Grid View control to Excel:

HtmlForm htmlForm = new HtmlForm();
string fileName = "attachment; filename=Reports.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", fileName);
Response.ContentType = "application/ms-excel";
StringWriter strw = new StringWriter();
HtmlTextWriter htxtw = new HtmlTextWriter(strw);
htmlForm.Controls.Add(GridViewReports);
this.Controls.Add(htmlForm);
GridViewReports.RenderControl(htxtw);
Response.Write(strw.ToString());
Response.End(); 

2-Export data table to excel:

HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in table.Columns)
{
    context.Response.Write(column.ColumnName + ";");
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
    for (int i = 0; i < table.Columns.Count; i++)
    {
        context.Response.Write(row[i].ToString().Replace(";", string.Empty) + ";");
    }
    context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + name + ".csv");
context.Response.End();

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *