简体   繁体   English

从ashx文件导出到Excel

[英]Export to Excel from ashx file

I am trying to export to excel from an .ashx file called from a jquery event. 我试图从jquery事件调用的.ashx文件导出到excel。 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. 如果我使用asp.net click事件,它将很好地工作,但是从jquery来看,数据将返回到调用jquery事件。 For reasons that would take way too long to explain, I must use the ashx code. 出于无法解释的原因,我必须使用ashx代码。 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. 我已经尝试过使用Flush,End和CompleteRequest进行各种组合。 Same results (End errored out). 结果相同(错误结束)。

Thank you. 谢谢。

It seems you are missing the content-length header. 似乎您缺少content-length标头。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM