GridView导出到Excel

来源:互联网 发布:域名dns修改生效 编辑:程序博客网 时间:2024/05/21 22:33

 

方法1

//注:在.aspx文件中第一行<%%>中加入EnableEventValidation="false"

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CardSelect.aspx.cs" Inherits="PersonMag" EnableEventValidation="false" %>

 

//这里一定要引入命名空间

using System.Data.SqlClient;

//为导入Excel引入命名空间

using System.Drawing;

using System.IO;

using System.Text;

 

private void GridViewBind()

    {

        //GridView的绑定

    }

    private void Export(string FileType, string FileName)

    {

        //GridView导出到Excel,导出所有页

        Response.Charset = "GB2312";

        Response.ContentEncoding = System.Text.Encoding.UTF8;//换成UTF7编码出现乱码

        Response.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(FileName,System.Text.Encoding.UTF8).ToString());

        Response.ContentType = FileType;

        this.EnableViewState = false;

        StringWriter tw = new StringWriter();

        HtmlTextWriter hw = new HtmlTextWriter(tw);

        

        this.GridView1.AllowPaging = false;//取消分页

     this.GridView1.AllowSorting = false;//取消排序

   //this.GridView1.AutoGenerateColumns = true;//取消自动生成列

        this.GridViewBind();//GridView的独立绑定函数

 

        GridView1.RenderControl(hw);

        Response.Write(tw.ToString());

        Response.End();

    }

    protected void btnSqlToExcel_Click(object sender, EventArgs e)

    {

        //SqlToExcel按钮响应的事件

        Export("application/ms-excel", "信息表.xls");//第一个参数是导出的类型,第二个参数是导出表的名称

    }

    public override void VerifyRenderingInServerForm(Control control)

    {

        //重写此方法,确保程序运行时,指定的GridView控件总是位于<form runat="server">标记内

        //base.VerifyRenderingInServerForm(control);

}

 

原创粉丝点击