Wednesday 19 February 2014

how to export data in excel file

--> if you want to export data in excel file from Gridview that time do following

--> Gridview name is gvProjects
--> copy the following function in your code behind file
------------------------------------------------------------------------------------------------

public void ExportData()
{
        Reponse.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "AllProject.xls"));//set your download file name
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        Response.Write(sw.ToString());
        Response.Write(" \nProject Information \n \n");
        Response.Write("Project Name  \t   Project Start Date \t  Project End Date \t  Project Description \t \t \t Client Name");
        Response.Write("\n");
            DataSet ds = new DataSet();
            ds=FillGridview();
        for (int i = 0; i < gvProjects.Rows.Count; i++)
        {
           
            Response.Write(ds.Tables[0].Rows[i]["Proj_Name"].ToString() + " \t  " + ds.Tables[0].Rows[i]["Proj_StartDate"].ToString() + " \t  " + ds.Tables[0].Rows[i]["Proj_EndDate"].ToString() + " \t  " + ds.Tables[0].Rows[i]["Proj_Desc"].ToString() + " \t \t \t " + ds.Tables[0].Rows[i]["Client_FullName"].ToString() );
    // above line change the filed name which is available in your table
            Response.Write("\n");
        }
        Response.End();
}

--> create following method for fill Gridview

 ------------------------------------------------------------------------------------------------


public void FillGridview()

{
    cmd = new SqlCommand("select * from Table_name", cn);
    da = new SqlDataAdapter(cmd);
    ds = new DataSet();
    da.Fill(ds);

    gvProjects.DataSource = ds;   //give dataset to gridview
    gvProjects.DataBind();         // binding gridview
   
}

--> above function call where you want to export data

No comments:

Post a Comment



Asp.net tutorials