Wednesday, November 30, 2011

How to export gridview data to excel in asp.net?

Here we will discuss how to export the gridview data into excel. There might be a chance that you have a lot of columns in your dataset or datatable but you want to show only those records that are showing in the gridview only. So here is the code to export gridview data to excel in asp.net.

protected void btnExport_Click(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        ds = GetDataForGridView();
        string attachment = attachment = "attachment; filename=MyExcelSheetName_" + DateTime.Now.ToString() + ".xls";
        if (ds.Tables.Count > 0)
        {
            DataTable dt = ds.Tables[0];
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/vnd.ms-excel";
            string tab = "";
            //This will give you the number of columns present in gridview
            for (int coulumns = 0; coulumns < GridView1.Columns.Count; coulumns++)
            {
                Response.Write(tab + GridView1.Columns[coulumns].HeaderText);
                tab = "\t";
            }

            Response.Write("\n");

            //Here we will visit each row of datatable and bind the corresponding column data.
            foreach (DataRow dr in dt.Rows)
            {
                tab = "";
                Response.Write(tab + dr["ColumnName1"].ToString());
                tab = "\t";

                Response.Write(tab + dr["ColumnName2"].ToString());
                tab = "\t";

                Response.Write(tab + dr["ColumnName3"].ToString());
                tab = "\t";

                Response.Write("\n");
            }
            Response.End();
        }
    }