在ashx中使用byte[]数组创建Excel文件以供客户端下载

3

我正在尝试在ashx文件中使用DataTableReader从DataTable中读取数据,然后将其转换为byte[]数组,创建Excel文件。但是它并没有起作用。这里是一些代码:

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

它抛出以下异常:
context.Response.SubStatusCode 抛出了 System.PlatformNotSupportedException 类型的异常。{"此操作需要 IIS 集成管道模式。"} ashx
我知道如果使用头文件需要 IIS7 或 Framework 3+。
非常感谢您的帮助!
1个回答

0

你设置了ResponseContentType,然后清除了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());    
    }
...

它抛出了这个异常:'context.Response.Headers' 抛出了一个 'System.PlatformNotSupportedException' 类型的异常。 - Tobi James
嗯,你的应用程序池是否处于集成模式?如果不是,请尝试使用集成模式。 - danielQ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接