ASP.NET中GridView中的数据导出到Excel表中程序段

#region 导出为Excel
    public override void VerifyRenderingInServerForm(Control control)
    {
        // Confirms that an HtmlForm control is rendered for
    }

    private void ToExcel(Control ctl, string FileName)
    {
        HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
        ctl.Page.EnableViewState = false;
        System.IO.StringWriter tw = new System.IO.StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        ctl.RenderControl(hw);
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
    }

    private void toExcelClk()
    {
        gvSysUser.AllowPaging = false;
        gvSysUser.AllowSorting = false;
        gvSysUser.DataBind();
        ToExcel(gvSysUser, "OFS_Data.xls");
        gvSysUser.AllowPaging = true;
        gvSysUser.AllowSorting = true;
        gvSysUser.DataBind();
    }
    #endregion

posted @ 2012-06-01 15:31  萧小米  阅读(64)  评论(0)    收藏  举报