关闭

将gridview的内容导出到excel中去

659人阅读 评论(0) 收藏 举报

 asp.net 2.0中,gridview控件是个很不错的控件,如何将gridview中的数据导出到EXCEL中去呢?特别是当gridview中的数据是分页显示时,要将整个gridview的数据导出到EXCEL中去呢?下面是解决的办法:
下面是部分代码片段:
defualt.aspx中,添加一个gridview控件
  <form id="form1" runat="server">
    <div>
        &nbsp;
        <asp:GridView ID="GridView1" runat="server" AllowPaging="true" OnPageIndexChanging="paging">
        </asp:GridView>
   
    </div>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="导出到excel" />
    </form>

default.aspx
  protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindData();
        }

    }
   
    private void BindData()
    {
        // make the query
        string query = "SELECT * FROM customers";
        SqlConnection myConnection = new SqlConnection(ConnectionString);
        SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
        DataSet ds = new DataSet();
        ad.Fill(ds, "customers");
        GridView1.DataSource = ds;
        GridView1.DataBind();

   }


    public override void VerifyRenderingInServerForm(Control control)
    {

        // Confirms that an HtmlForm control is rendered for

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();

        Response.AddHeader("content-disposition",
        "attachment;filename=FileName.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);

       
        GridView1.AllowPaging = false;
        BindData();
        GridView1.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());

        Response.End();

        GridView1.AllowPaging = true;
        BindData();

    }
    protected void paging(object sender,GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindData();
    }

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3647次
    • 积分:52
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:4篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档