Export GridView to Word Using Asp.net C#

Background

Many times their is a need in a project's reporting module to show Records of Gridview into MS office word, So by considering the above requirement I decided to write this article especially focusing on beginners and those who want to learn how Export Gridview to MS office word Using Asp.net C#

Now before creating the application, let us create a table named employee in a database to from we show the records in a Gridview ,the table having the following fields (shown in the following image):
 
 
 
I hope you have created the same type of table.
 
Now create the project as:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
  3. Give the Project name such as ExportGridToword or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - Default.aspx page.
  5. one Buttons, one label and a grid view.

Now let us create function to bind the records to Grid view from Database, If you are beginner and don’t know in details how to bind Grid view from database then refer my following article.

now, for this article create the following function into the default.aspx.cs page to bind the Grid view

  1. private void Bindgrid()    
  2. {    
  3.     connection();    
  4.     query = "select *from Employee";//not recommended this i have wrtten just for example,write stored procedure for security    
  5.     com = new SqlCommand(query, con);    
  6.     SqlDataReader dr = com.ExecuteReader();    
  7.     GridView1.DataSource = dr;    
  8.     GridView1.DataBind();    
  9.     con.Close();       
  10.                  
  11. } 
now, call this function on page load as
  1. protected void Page_Load(object sender, EventArgs e)    
  2. {    
  3.     if (!IsPostBack)    
  4.     {    
  5.         Bindgrid();    
  6.         
  7.     }    
  8. }
now run the application,then we can see the following records in Grid view as
 
 
Now ,we have record to export into MS office word,let us start coding for our actual requirement..,add the VerifyRenderingInServerForm event after the page load which is required while exporting Grid view to excel,word and PDF to avoid the run time error which is occurred like as "GridView' must be placed inside a form tag with runat=server."
  1. public override void VerifyRenderingInServerForm(Control control)    
  2. {    
  3.     //required to avoid the runtime error "    
  4.     //Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."    
  5. } 
now create the following function to Export the grid view to MS office word as
  1. private void ExportGridToword()    
  2. {    
  3.     Response.Clear();    
  4.     Response.Buffer = true;    
  5.     Response.ClearContent();    
  6.     Response.ClearHeaders();    
  7.     Response.Charset = "";    
  8.     string FileName = "Vithal" + DateTime.Now +".doc";    
  9.     StringWriter strwritter = new StringWriter();    
  10.     HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);          
  11.     Response.Cache.SetCacheability(HttpCacheability.NoCache);    
  12.     Response.ContentType ="application/msword";    
  13.     Response.AddHeader("Content-Disposition","attachment;filename=" + FileName);    
  14.     GridView1.GridLines = GridLines.Both;    
  15.     GridView1.HeaderStyle.Font.Bold = true;    
  16.     GridView1.RenderControl(htmltextwrtter);    
  17.     Response.Write(strwritter.ToString());    
  18.     Response.End();        
  19.   
  20. } 

Now double click on Export  button and call the above function on "onclick"as

  1. protected void Button1_Click(object sender, EventArgs e)    
  2. {    
  3.     ExportGridToword();    
  4. } 
Now the whole code of Default.aspx.cs page will be as follows
  1. using System;    
  2. using System.Web.UI;    
  3. using System.Web.UI.WebControls;    
  4. using System.Configuration;    
  5. using System.Data.SqlClient;    
  6. using System.IO;    
  7. using System.Web;    
  8.     
  9. public partial class _Default : System.Web.UI.Page    
  10. {    
  11.     private SqlConnection con;    
  12.     private SqlCommand com;    
  13.     private string constr,query;    
  14.     private void connection()    
  15.     {    
  16.         constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();    
  17.         con = new SqlConnection(constr);    
  18.         con.Open();    
  19.         
  20.     }    
  21.     protected void Page_Load(object sender, EventArgs e)    
  22.     {    
  23.         if (!IsPostBack)    
  24.         {    
  25.             Bindgrid();    
  26.             
  27.         }    
  28.     }    
  29.     
  30.     public override void VerifyRenderingInServerForm(Control control)    
  31.     {    
  32.         //required to avoid the runtime error "    
  33.         //Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."    
  34.     }    
  35.     
  36.     private void Bindgrid()    
  37.     {    
  38.         connection();    
  39.         query = "select *from Employee";//not recommended this i have wrtten just for example,write stored procedure for security    
  40.         com = new SqlCommand(query, con);    
  41.         SqlDataReader dr = com.ExecuteReader();    
  42.         GridView1.DataSource = dr;    
  43.         GridView1.DataBind();    
  44.         con.Close();       
  45.                      
  46.     }    
  47.     protected void Button1_Click(object sender, EventArgs e)    
  48.     {    
  49.         ExportGridToword();    
  50.     }    
  51.     private void ExportGridToword()    
  52.     {    
  53.         Response.Clear();    
  54.         Response.Buffer = true;    
  55.         Response.ClearContent();    
  56.         Response.ClearHeaders();    
  57.         Response.Charset = "";    
  58.         string FileName = "Vithal" + DateTime.Now +".doc";    
  59.         StringWriter strwritter = new StringWriter();    
  60.         HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);          
  61.         Response.Cache.SetCacheability(HttpCacheability.NoCache);    
  62.         Response.ContentType ="application/msword";    
  63.         Response.AddHeader("Content-Disposition","attachment;filename=" + FileName);    
  64.         GridView1.GridLines = GridLines.Both;    
  65.         GridView1.HeaderStyle.Font.Bold = true;    
  66.         GridView1.RenderControl(htmltextwrtter);    
  67.         Response.Write(strwritter.ToString());    
  68.         Response.End();  
  69.     }  
  70. }   
Now run the application and click on Export Button, the following popup is appeared as
 
 
Now click on open with option, then you can see that all grid view records will be exported into MS office word as
 

Note
  • Download the zip file from the attachment for the full source code of an application.
  • change connection string from web.config file as per your server location.

Summary

I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.