I am exporting a gridview to excel, using .Net 4.0 in a web application, on page load and need for the file to be generated and then the page to be redirected to the calling page. I am running into issues because my code to export to excel is as follows:
gvSummary.Style.Add("font-size", ".6em");
Response.Clear();
string attachment = "attachment; filename=filename.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvSummary.GridLines = GridLines.Horizontal;
gvSummary.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
I know that if I put the Response.Redirect() before the .End(), I will get redirected but the file is never generated, and if I put the Response.Redirect() after the .End() I get the file but no redirection.
The code written above works just fine in generating the file, however when after the file is generated I am still stuck seeing my Loading animation because I can not break out of the page. Any ideas?
Response. Redirect sends an HTTP request to the browser, then the browser sends that request to the web server, then the web server delivers a response to the web browser. For example, suppose you are on the web page "UserRegister. aspx" page and it has a button that redirects you to the "UserDetail.
Redirect has EndResponse value is true. Response. Redirect("Default. aspx", false) means current page execution is not terminated and code written after the Response.
Transfer: It transfers execution from the first page to the second page on the server.
I suggest to add a redirect header. Something like this:
Response.AddHeader("Refresh", "3; url=index.html");
Where 3 is time of the delay and index.html is url you need to redirect to
The problem is Response.End() send the last bits of the page to the client in order to complete the request. In your case, the request contains the file.
One possible solution is be to open a new page for the download and keep the redirect in the current page.
I added the target="_blank"
to the link that takes me to the page. So when it opens in a new window, it send the excel sheet to the browser, and closes the page as it has nothing else to do after the Response.End();
Hope this helps. Worked for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With