0

The following method, based on code in this question, shows a file download dialog box in the browser, but then the download never starts (it stays at 0%):

protected void lnkExport_Click(object sender, EventArgs e) {
  var bytes = Encoding.ASCII.GetBytes(SelectRecords()); //Data to be downloaded
  Response.Clear();
  Response.ContentType = "application/vnd.ms-excel";
  Response.AddHeader("Content-Disposition", "attachment; filename=\"test.xls\"");
  using (var stream = new MemoryStream(bytes)) {
    Response.AddHeader("Content-Length", stream.Length.ToString());
    stream.WriteTo(Response.OutputStream);
  }
}

Any idea what's up?

Community
  • 1
  • 1
James
  • 7,343
  • 9
  • 46
  • 82
  • That's not an Excel file, and you shouldn't lie and say that it is. – SLaks Sep 11 '11 at 13:44
  • 1
    True, SelectRecords() actually returns an HTML table. However, the intention is that Excel should open it (which it can) and the easiest way is to give it an .xls extension. :) – James Sep 11 '11 at 13:46
  • I believe that that will result in an Excel security warning. – SLaks Sep 11 '11 at 13:48

1 Answers1

3

Your code worked fine for me but you may want to try adding this as the last line of your click handler:

Response.End();
joshb
  • 5,182
  • 4
  • 41
  • 55
  • Actually it was an HttpModule trying to GZip the Response stream, so I had to set Response.Filter = null; and Response.ClearHeaders(); However your answer led me to this since you said the code worked for you! – James Sep 11 '11 at 20:11