Pages

Subscribe:

Ads 468x60px

Friday, March 16, 2012

how to export data into MS Word File from grid view in asp.net using c#

In this web programming tutorial we will learn that how we can export data into MS word file from grid view by clicking a button in asp.net using c#
Code for .aspx file

   
    
    
    
    
   

Code for .CS file
protected void btnExportWord_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
    "attachment;filename=GridViewExport.doc");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-word ";
    StringWriter sw= new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    GridView1.RenderControl(hw);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}

To avoid the error you will need to add this event which ensures that the GridView is Rendered before exporting.
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

No comments:

Post a Comment