views:

163

answers:

3

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?

+2  A: 

I suggest to add a redirect header. Something like this:

Response.AddHeader("Refresh", "3; url=index.html");

Where 3 is time delay and index.html is url you need to redirect to

ILya
Since the result of the request is a xls file and not html, will that really work ?
Fredrik Leijon
I think yes. because first of all HTTP is used to deliver response. In this case HTTP package looks like a set of headers followed by binary data (xls file). In some cases adiitionaly it will be necessary to set contnt type to application/octet-stream but it depends on what kind of result do we need
ILya
It did not work, it would load the file but not redirect...
EvanGWatkins
hmm.. Try to set Refresh header directly after Response.ClearContent() so it must be the first header to set
ILya
@EvanGWatkins I think the problem is in the flow you are using, see my answer.
eglasius
+1  A: 

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.

Johann Blais
A: 

You can't do both open so you might want to try setting the link to the generated xls file in a new window or as source to a iframe

Fredrik Leijon