Eport dynamic data from div to excel in asp.net using jquery and c# | How to Export data to excel

export-dynamic-data-from-div-to-excel.aspx




















id Name Birth Date Gender
1 Adeel Fakhar 15/10/1984 male
2 Omer Fakhar 01/09/1986 male

Let's suppose the table inside the div is populated dynamically from database. You may use inside div, it is up to you. Now let's have a look over the hidden field just before the . Using that hidden field I am exporting dynamically div data to excel. In javascript custom function, i am using jquery to get all the inner html of the div, removing all the extra spaces by using built-in jquery trim() function and then replacing > to > and < to < so that data can be transfer to server without any html injection. After replacing the > to > and < to < I am storing all the div data to hidden field and when focus will go to server side then the function ExportToExcel() will export the div data to excel. ExportToExcel() function is self explanatory. In this function I am converting > back to > and < back to < and using Response.Header all the data is being exported to excel.

.cs
protected void Button1_Click(object sender, EventArgs e)
{
string html = HdnValue.Value;
ExportToExcel(ref html, "MyReport");
}


public void ExportToExcel(ref string html, string fileName)
{
html = html.Replace(">", ">");
html = html.Replace("<", "<");
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName + "_" + DateTime.Now.ToString("M_dd_yyyy_H_M_s") + ".xls");
HttpContext.Current.Response.ContentType = "application/xls";
HttpContext.Current.Response.Write(html);
HttpContext.Current.Response.End();
}
So this is the proper way to export dynamic data from div to excel in asp.net using jquery and c#.

0 comments:

Post a Comment