Monday, 14 July 2014

How to export data grid view to excel 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.xls","application/vnd.ms-excel");

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

for exporting to .xlsx file use "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" instead of "application/vnd.ms-excel" and change the file extension as "myfile.xlsx"

No comments:

Post a Comment