Search code examples
c#asp.netashx

Export to Excel from ashx file


I am trying to export to excel from an .ashx file called from a jquery event. My data is prepared correctly. but I'm not prompted to save. If I use the asp.net click event, it works perfectly, but from the jquery, the data goes back to the calling jquery event. For reasons that would take way too long to explain, I must use the ashx code. What do I need to do?

context.Response.ClearHeaders();
context.Response.Clear();
context.Response.ClearContent();
string attachment = "attachment; filename='UserRolesPermissions.xls'";
context.Response.AddHeader("content-disposition", attachment);
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.Write(excelData);
context.Response.Flush(); 
context.ApplicationInstance.CompleteRequest();

I've tried various combinations using Flush, End and CompleteRequest. Same results (End errored out).

Thank you.


Solution

  • It seems you are missing the content-length header. This could make a difference.

    //make sure the data is a byte array
    byte[] bin = excelData;
    
    context.Response.ClearHeaders();
    context.Response.Clear();
    context.Response.Buffer = true;
    context.Response.ContentType = "application/vnd.ms-excel";
    context.Response.AddHeader("content-disposition", "attachment; filename=\"UserRolesPermissions.xls\"");
    
    //this could help
    context.Response.AddHeader("content-length", bin.Length.ToString());
    context.Response.OutputStream.Write(bin, 0, bin.Length);
    
    context.Response.Flush();
    context.ApplicationInstance.CompleteRequest();