从byte 数组中为ashx创build一个excel文件以供客户端下载

我想从一个byte []数组中创build一个Excel文件后,使用DataTableReader从DataTable中读取数据,所有这些都在ashx文件中。 但它只是不工作。 在这里,我张贴一些代码:

DataTableReader RS = dt.CreateDataReader(); byte[] byteArray = GetData(RS); context.Response.ContentType = "application/ms-excel"; context.Response.Clear(); // context.Response.Charset = ""; try { context.Response.BinaryWrite(byteArray); context.Response.OutputStream.Write(byteArray, 0, byteArray.Length); context.Response.BufferOutput = true; context.Response.Flush(); } catch (Exception ex) { SendMail(ex.Message.ToString()); } 

它引发以下exception:

context.Response.SubStatusCode抛出了System.PlatformNotSupportedExceptiontypes的exception。 {“这个操作需要IIS集成pipe道模式。”} ashx

我知道,如果我使用头需要有IIS7或框架3+。

任何帮助,将不胜感激!!

您设置Response ContentType然后Clear Response 。 然后你写回应两次,这也是奇怪的。 我会改变这一点,我也会尝试调用End而不是Flush

最低限度的代码,以使其工作将是这样的:

 ... DataTableReader RS = dt.CreateDataReader(); byte[] byteArray = GetData(RS); try { context.Response.Clear(); context.Response.ContentType = "application/ms-excel"; context.Response.OutputStream.Write(byteArray, 0, byteArray.Length); context.Response.End(); } catch (Exception ex) { SendMail(ex.Message.ToString()); } ... 

您是否为Excel文档添加了MIMEtypes? 另外,请查看这篇文章。 设置mimetypes为excel文件

Interesting Posts