Saturday, November 1, 2008

How to Export To Excel in ASP.NET

Export Gridview 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(); 

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();

Hire Me

Follow me on Facebook

Follow me

Do you find this Blog helpful?

Follow by Email

About Me

My Photo
Expert Senior Software Developer

Microsoft Business Card