发送excel表作为响应

时间:2012-12-14 12:00:26

标签: c# .net excel excel-2007

我创建了excel表并使用

保存
xlWorkBook.SaveCopyAs("abc.xls");

然后我正在使用

 byte[] byteArray = File.ReadAllBytes("abc.xls");
 File.Delete("abc.xls");
 Response.ContentType = "application/vnd.ms-excel";
 Response.AppendHeader("Content-Disposition", "attachment; filename=abc.xls");
 Response.BinaryWrite(byteArray);
 Response.End();

将Excel工作表作为回复发送。

但问题是在客户端它首先提示保存excel工作簿“Book1”然后它提示保存“abc.xls”。如何防止?

早些时候我正在使用

xlWorkBook.SaveAs("abc.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

它工作正常(直接提示保存“abc.xls”)。但我改为xlWorkBook.SaveCopyAs()因为xlWorkBook.SaveAs()在IIS中部署时抛出了异常

1 个答案:

答案 0 :(得分:0)

我有我的代码

    string fileName = "xyz.xls";

    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
    HttpContext.Current.Response.ContentType = "application/vnd.xls";           

    /*      
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter htw = new HtmlTextWriter(sw))
        {
            //extract
        }
    }
    */


    HttpContext.Current.Response.Write(sw.ToString());
    HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.End();