首页 > 代码库 > 强制下载excel

强制下载excel

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="filepath">导出的文件路径</param>
        /// <param name="filename"></param>
        public static void DownLoadFile(HttpContextBase context, string filepath,string filename)
        {

            System.IO.FileInfo file = new System.IO.FileInfo(filepath);
            context.Response.Clear();
            context.Response.Charset = "GB2312";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            // 添加头信息,为"文件下载/另存为"对话框指定默认文件名 
            context.Response.AddHeader("Content-Disposition", "attachment; filename=" + context.Server.UrlEncode(filename));
            // 添加头信息,指定文件大小,让浏览器能够显示下载进度 
            context.Response.AddHeader("Content-Length", file.Length.ToString());

            // 指定返回的是一个不能被客户端读取的流,必须被下载 
            context.Response.ContentType = "application/ms-excel";

            // 把文件流发送到客户端 
            context.Response.WriteFile(file.FullName);

            //System.IO.File.Delete(path + fileName);//删除临时文件

            // 停止页面的执行 
            context.Response.End();
            

        }