Bulk Export Data To Excel using Gridview

Posted by Unknown On Wednesday, December 17, 2014 0 comments

Fast, Short and Easy way to generate gridview to excel. You can also get rid of unnessary controls like check box, button, and select link etc, but you can if you want to.

c#
    private void ExportToExcel()
    {
        string attachment = "attachment; filename=statement.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        System.IO.StringWriter sw = new System.IO.StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView newGrid = new GridView();

        //if you want to copy old gridview column
        //DataControlFieldCollection columns = OldGridView.Columns;
        //foreach (DataControlField col in columns)
        //{
        //    newGrid.Columns.Add(col);
        //}

        //if you want to manage columns on your own
        //newGrid.Columns.Add(new BoundField { DataField = "CreateDate", HeaderText = "Created Date" });
        //newGrid.AutoGenerateColumns = false;
            
        newGrid.DataSource = SqlDataSource1.Select(DataSourceSelectArguments.Empty) as DataView;
        newGrid.DataBind();

        newGrid.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();        
    }

0 comments:

Post a Comment