Export table to Excel using jQuery in IE
To make it work for IE with ASP.NET, we need to append header in Response object and then allow downloading of file. This can't be done only on client side for IE. So the idea is to pass the table data along with its structure to ASP.NET server side code and then using server side code, allow downloading of file. But before passing the data to server, escape the HTML tags to handle "A potentially dangerous Request. Form value was detected from the client" exception.
Below
$(document).ready(function () { $("#btnExport").on('click', function (e) { var tblHTML = $("#dvData").html(); tblHTML = escape(tblHTML); $('#hdnData').val(tblHTML); }); });
And below is ASP.NET server side button click code, which adds header to Response object and defines the content type to "application/excel". And then writes the data.
protected void btnExport_Click(object sender, EventArgs e) { string data = hdnData.Value; data = HttpUtility.UrlDecode(data); Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=Data.xls"); Response.Charset = ""; Response.ContentType = "application/excel"; HttpContext.Current.Response.Write(data); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); }
Feel free to contact me for any help related to jQuery, I will gladly help you.