Create an excel file in ashx from byte[] array for client download

I'm trying to create an Excel file from a byte[] array after reading the data from a DataTable using a DataTableReader, all this in a ashx file. But it's just not working. Here I post some code:

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());
 }

It throws the following exception:

context.Response.SubStatusCode threw an exception of type System.PlatformNotSupportedException. {"This operation requires IIS integrated pipeline mode."} ashx

I know that if I use the headers need to have IIS7 or Framework 3+.

Any help would be appreciated!!


You set the Response ContentType and then Clear the Response . Then you write the response two times, that's odd too. I would change that, and I would also try calling End instead of Flush .

The minimun amount of code to get it working would be something like:

...
    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());    
    }
...

did you add a MIME type for excel documents? also, check this article out Setting mime type for excel document

链接地址: http://www.djcxy.com/p/46852.html

上一篇: 错误:MIME类型文本/ csv

下一篇: 从byte []数组中为ashx创建一个excel文件以供客户端下载