GridView导出到Excel

来源:互联网 发布:r语言与数据分析实战 编辑:程序博客网 时间:2024/06/07 01:32
protected void Button1_Click(object sender, EventArgs e) //导出
        {
            Export("application/ms-excel", "info.xls"); //现在导出Excel,如需要导出word,只需要将application/ms-word 更改即可。第二个参数代表导出后文件的名称以以及格式
        }

        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();
        }

        public override void VerifyRenderingInServerForm(Control control) //必加事件,不加会报“类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内”错误
        {
        }
原创粉丝点击