I'm trying to make it possible for the user to download an Excel spreadsheet from our site, by having a button that redirect through this:
Response.Redirect(string.Format("../excel/ExcelForm.aspx?pathName=&fileNameDisplay={0}&fileNameUnique={1}", "spreadsheet.xls", fileName));
The aspx page just sends back the file through the Response object, like this:
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileNameDisplay);
Response.WriteFile(Server.MapPath(pathName + fileNameUnique));
Response.Flush();
Response.End();
Everything works just fine on my machine, but when we're putting it on the server, the https in combination with no-cache settings gives us an error saying "Internet Explorer cannot download [blahblahblah]". The cache settings on the page displaying the excel button:
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Expires = 0;
HttpContext.Current.Response.AddHeader("Pragma", "no-cache");
HttpContext.Current.Response.AddHeader("cache-control", "private, no-cache, must-revalidate no-store pre-check=0 post-check=0 max-stale=0");
HttpContext.Current.Response.Cache.SetNoServerCaching();
When I remove those lines, everything works just fine. However, I'm not allowed to remove them for other reasons. So I tried adding the following line to the ExcelForm.aspx just before it adds stuff to the header:
Response.ClearHeaders();
Which just gives me "Internet Explorer cannot download ExcelForm.aspx from [url]". And that's where I'm stuck. Suggestions?
I had a similar problem myself recently when exporting CSV files from an MVC controller method. I found that adding:
Response.ClearHeaders();
Response.Clear();
Solved the problem for me in IE
Hope this helps!
I also faced the same issue,
When I googled it, I found that "no chache" settings in response header i.e. following code is the reason for the issue.
Response.AppendHeader("Pragma", "no-cache")
Response.AppendHeader("Cache-Control", "no-cache")
Response.AppendHeader("max-age", "0")
Some of the blogs says, to fix this issue, you should do some modification in Windows registry on Webserver and on all client machines(:O), well it is not feasible to do registry settings on every client machine.
The root cause is no-cache settings in response header, so I just added
Response.ClearHeaders()
before adding content to be downloaded to the response header. The code is as shown below,
Response.ClearHeaders()
Response.ContentType = "application/ms-excel"
Response.AppendHeader("content-disposition", "attachment; filename=""" + fileName + """")
Response.BinaryWrite(fileBytes)
Response.End()
It has fixed the issue.
Enjoy!!!
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