如何从aspx网页下载excel文件

时间:2017-07-26 09:37:11

标签: c# asp.net excel sql-server-2008

我正在尝试从aspx网页上从数据库中获取以字节为单位存储的excel文件,并以.xls格式下载并打开,但该文件将以.aspx的形式下载。如何解决这个问题?

我试过了:

    private void download(DataTable dt)
    {


        if (dt.Rows.Count > 0)
        {
            Byte[] bytes = (Byte[])dt.Rows[0]["xyz"];
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.ms-excel";
            Response.BinaryWrite(bytes);
           // Response.Flush();
            Response.End();
        }
    }

1 个答案:

答案 0 :(得分:1)

您需要设置Content-Disposition标头。例如:

Content-Disposition: attachment; filename=your-excel-file.xlsx

在代码中:

Response.AddHeader("Content-Disposition", "attachment; filename=your-excel-file.xlsx");