Monday, 14 July 2014

How to export data grid view to doc file?


To export data grid view to excel file follow these steps:

  1. Write a function export( ) as:

 private void export(string filename, string type)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=" + filename);
            Response.Charset = "";
            Response.ContentType = type;
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            GridView1.RenderControl(hw);      //render the gridview 
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.Close();
            Response.End();


        }

here name of our grid view is GridView1  so we have used GridView1.RenderControl(hw);
  1. Write public override void and select  VerifyRenderingInServerForm(Control control) from intelisense, function will displayed as:
 public override void VerifyRenderingInServerForm(Control control)
        {
            base.VerifyRenderingInServerForm(control);
        }

Now comment the line in function as:

public override void VerifyRenderingInServerForm(Control control)
        {
          //  base.VerifyRenderingInServerForm(control);
        }


We have done this for rendering of data grid view


  1. Now call the function export( )  on button_click( ) as:
export("myfile.doc","application/msword");

the file will be saved as myfile.doc you can specify other name for file also.

for exporting to .docx file use "application/vnd.openxmlformats-officedocument.wordprocessingml.document" instead of "application/msword" and change the file extension as "myfile.docx"

No comments:

Post a Comment