GridView Execl导出

 protected void Button1_Click(object sender, EventArgs e)
    {
        DGToExecl(GridView1);
    }
    /// <summary>
    /// 导出Execl文档
    /// </summary>
    /// <param name="ctl"></param>
    public void DGToExecl(System.Web.UI.Control ctl) {
        Response.Clear();
        //是否缓冲输出
        Response.Buffer = true;
        //导出路径
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Execl.xls");
        //编码格式
        HttpContext.Current.Response.Charset = "UTF-8";
        //html字符集
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
        //Http MIME类型
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        //是否保存视图状态
        ctl.Page.EnableViewState = false;
        //区域设置
        System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
        //写入字符串
        System.IO.StringWriter tw = new System.IO.StringWriter(myCItrad);
        //格式设置
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
        //内容输出
        ctl.RenderControl(hw);
        //写入输出流
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
    }
    //重载VerifyRenderingInServerForm方法 原因:如果不重载的话再内容输出的时候会报错
    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    } 

 

 

 

posted on 2012-04-23 10:58  水行者  阅读(230)  评论(0编辑  收藏  举报

导航