Wednesday 19 February 2014

code for export data in MS-Word file

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

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

public void ExportData()
{
        Reponse.ClearContent();
        string FName = "filename.doc";
            mygrid.AllowPaging = false;
            mygrid.DataSource = datasource();
            mygrid.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", FName));
            //set your download file name
            Response.Charset = "";
            Response.ContentType = "application/ms-word";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            mygrid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
          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 use where you want to export data or Click event

No comments:

Post a Comment



Asp.net tutorials