Tags

, , , ,


AJAX Asp.net Page and Export to Excel, CSV, Word

If we are using AJAX Update panel, and Export button inside the update panel, and want to export GridVew data into Excel, CSV or Word documents..!!
Follow the Following steps::

1. Register the Export button trigger with update panel.

<asp:UpdatePanel .. .. .. >
<ContentTemplate >
.. ..
.. ..
.. ..
</ContentTemplate/>
<Triggers>
<asp:PostBackTrigger ControlID=”btnExport” />
</Triggers>
</asp:UpdatePanel>

2. Write the following methods to export data in CS file.
//Export Button Click Event
protected void btnExport_Click(object sender, EventArgs e)
{
switch (ddlExportType.SelectedItem.Value.ToString())
{
case “EXL”:
gridView.ExportToExcel(ExportType.Excel);
break;
case “WRD”:
gridView.ExportToExcel(ExportType.Word);
break;
case “CSV”:
gridView.ExportToExcel(ExportType.CSV);
break;
default:
gridView.ExportToExcel(ExportType.Excel);
break;
}
}

//Verify Rendering In Server Form
public override void VerifyRenderingInServerForm(Control control)
{
}

//Extension Method for GridView to export the Data
public static void ExportToExcel(this GridView gridView, ExportType etType)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
string strCurrentResponseContentType = string.Empty;
string strFileName = string.Empty;

switch (etType)
{
case ExportType.Excel:
strCurrentResponseContentType = string.Format(@”application/vnd.ms-excel”);
strFileName = DateTime.Now.ToString() + “.xls”;
break;
case ExportType.CSV:
strCurrentResponseContentType = string.Format(@”text/csv”);
strFileName = DateTime.Now.ToString() + “.csv”;
break;
case ExportType.Word:
strCurrentResponseContentType = string.Format(@”application/vnd.ms-word”);
strFileName = DateTime.Now.ToString() + “.doc”;
break;
default:
strCurrentResponseContentType = string.Format(@”application/excel”);
strFileName = DateTime.Now.ToString() + “.xls”;
break;
}
HttpContext.Current.Response.ContentType = string.Format(strCurrentResponseContentType);
string stc = String.Format(@”attachment;filename={0}”, strFileName);
HttpContext.Current.Response.AddHeader(@”content-disposition”, stc);
HttpContext.Current.Response.Charset = @””;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
gridView.RenderControl(htw);

HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}

//Enum for Export Types
public enum ExportType
{
CSV, Excel, Word
}

Advertisements