GridView数据导出到Excel中

自定一个方法

 private void Export(string FileType, string FileName)
    {
        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        GridView1.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();
    }


在GridView旁添加一个导出按钮

protected void Button1_Click(object sender, EventArgs e)
    {
        Export("application/ms-excel", "学生成绩报表.xls");
    }


不可缺少的一个(/如果没有下面方法会报错类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内

 public override void VerifyRenderingInServerForm(Control control)
    {
    }

另外还要引入命名空间IO和Text

你可能感兴趣的:(GridView数据导出到Excel中)