玄铁剑

成功的途径:抄,创造,研究,发明...
posts - 128, comments - 42, trackbacks - 0, articles - 174

GridView下载成Excel(IE6/IE7正常显示)

Posted on 2008-12-22 20:27 玄铁剑 阅读(567) 评论(0)  编辑 收藏 引用 所属分类: asp.net
        //public override void VerifyRenderingInServerForm(Control control)
        //{
        //}
        static public void DownLoadFile(GridView gvToExcel, string strTrueFileName)
        {
            HttpServerUtility CurrentServer = HttpContext.Current.Server;
            HttpResponse CurrentResponse = HttpContext.Current.Response;
            string strPath = UDF.GetAppSettingValue(UdfType.TempOutputPath);
            string strFile = CurrentServer.MapPath(strPath) + strTrueFileName;
            FileInfo file;
            if (File.Exists(strFile))
            {
                file = new FileInfo(strFile);
                file.IsReadOnly = false;
                file.Delete();
            }
            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            gvToExcel.RenderControl(htmlWrite);
            FileStream fs = File.Create(strFile);
            byte[] info = new UTF8Encoding(true).GetBytes(stringWrite.ToString());
            fs.Write(info, 0, info.Length);
            fs.Close();
            file = new FileInfo(strFile);
            CurrentResponse.Clear();
            CurrentResponse.ClearHeaders();
            CurrentResponse.Buffer = false;
            CurrentResponse.AddHeader("Content-Disposition", "attachment;filename=" + CurrentServer.UrlEncode(strTrueFileName));
            CurrentResponse.AddHeader("Content-Length", file.Length.ToString());
            CurrentResponse.ContentType = "application/octet-stream";//saveAs
            CurrentResponse.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7");
            CurrentResponse.WriteFile(strFile);
            CurrentResponse.Flush();
            CurrentResponse.End();
        }
只有注册用户登录后才能发表评论。