GridView 技巧3:将GridView数据导出到excel文件

在页面添加一个ID为ExportToExcelBtn的按钮,代码部分如下:


protected void ExportToExcelBtn_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=lessons.xls");
        Response.Charset = "gb2312";
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        gvLessons.AllowPaging = false;
        gvLessons.DataBind();
        gvLessons.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());
        Response.End();

        gvLessons.AllowPaging = true;
        gvLessons.DataBind();
    }
 要重载VerifyRenderingInServerForm方法,不然将报错
    public override void VerifyRenderingInServerForm(Control control) { }

posted on 2006-10-13 12:59  灵风  阅读(782)  评论(1编辑  收藏  举报