现在的位置: 首页 > 综合 > 正文

GridView导出到Excel

2018年02月11日 ⁄ 综合 ⁄ 共 928字 ⁄ 字号 评论关闭

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 的窗体标记内”错误
        {
        }

抱歉!评论已关闭.