How to bind and Export GridView data to Ms Word file using, VB.Net)

Introduction: In previous articles i explained  How to bind and Export GridView data to Ms Excel file  and Bind and Export GridView data to CSV file in and Bind and Export GridView data to PDF file in and  How to bind gridview using SqlDataAdapter, SqlCommand, DataSet and Stored procedure in and How to bind GridView from Xml DataSource and Highlight gridview row on mouse over using CSS in  and How to bind empty GridView with header and custom message when no data present in DataSet in .
 In this article I am going to explain with example how to Bind GridView and Export Gridview data to Ms Word file using  

Bind and Export GridView data to Ms Word in
Click on image to enlarge
Bind and Export GridView data to Ms word in
click on image to enlarge
Implementation: Let's create an sample application to understand.
  • First of all create a Database e.g. "MyDataBase" and a also create a table under that DataBase in Sql Server and name it "EMPLOYEE" as shown in figure:
Note: EMP_ID column is set to Primary key and Identity specification is set to yes with Identity increment and Identity seed equal to 1. Insert some data in this table that you  want to show in the Gridview.
  • Now in web.config file add the connection string under <configuration> tag :
    <add name="conStr" connectionString="Data Source=LocalServer;Initial Catalog=MyDataBase;Integrated Security=True"/>

Note: Replace the Data Source and the Initial catalog as per your applicaton.
  • In the design page (.aspx) place a GridView control to bind with data and a Button control to Export the GridView data to MS word file.
Source Code:

<fieldset style="width:360px;">
            <legend>Bind and Export GridView data to Ms Word in</legend>
                        <asp:GridView ID="grEmp" runat="server" AllowPaging="True" AutoGenerateColumns="False"
                   GridLines="None" Width="100%" CellPadding="4" ForeColor="#333333">
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />                   
                        <asp:BoundField DataField="EMP_NAME" HeaderText="Emp Name"  />
                        <asp:BoundField DataField="DEPT" HeaderText="Department"  />
                        <asp:BoundField DataField="SALARY" HeaderText="salary"  />
                        <asp:BoundField DataField="EMAIL_ID" HeaderText="Email Id" />
                    <EditRowStyle BackColor="#999999" />
                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <SortedAscendingCellStyle BackColor="#E9E7E2" />
                    <SortedAscendingHeaderStyle BackColor="#506C8C" />
                    <SortedDescendingCellStyle BackColor="#FFFDF8" />
                    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                         <asp:Button ID="btnExportToWord" runat="server" Text="Export To MS Word FIle" OnClick="btnExportToWord_Click" />                

C#.Net Code to Bind and Export GridView data to Ms word file

First include the following namespaces

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net;
using System.Net.Mail;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;

Then write the code as:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
        if (!Page.IsPostBack)
    public override void VerifyRenderingInServerForm(Control control)
        //It solves the error "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
    protected void BindEmpGrid()
        SqlCommand cmd = new SqlCommand("select * from EMPLOYEE", con);
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        grEmp.DataSource = dt;
    protected void btnExportToWord_Click(object sender, EventArgs e)
            Response.AddHeader("content-disposition", "attachment;filename=MyWordFile.doc");
            Response.Buffer = true;
            Response.Charset = "";
            Response.ContentType = "application/vnd.word";
            StringWriter strWrite = new System.IO.StringWriter();
            HtmlTextWriter htmWrite = new HtmlTextWriter(strWrite);        
            HtmlForm htmfrm = new HtmlForm();
            grEmp.AllowPaging = false;
            htmfrm.Attributes["runat"] = "server";
        catch (Exception ex){}      

VB.Net Code to Bind and Export GridView data to Ms word file

First import the following namespaces

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Net
Imports System.Net.Mail
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Text

Then write the code as:

  Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
        End If
    End Sub
    Public Overrides Sub VerifyRenderingInServerForm(control As Control)
        'It solves the error "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
    End Sub
    Protected Sub BindEmpGrid()
        Dim cmd As New SqlCommand("select * from EMPLOYEE", con)
        Dim dt As New DataTable()
        Dim adp As New SqlDataAdapter(cmd)
        grEmp.DataSource = dt
    End Sub
    Protected Sub btnExportToWord_Click(sender As Object, e As EventArgs)
            Response.AddHeader("content-disposition", "attachment;filename=MyWordFile.doc")
            Response.Buffer = True
            Response.Charset = ""
            Response.ContentType = "application/vnd.word"
            Dim strWrite As StringWriter = New System.IO.StringWriter()
            Dim htmWrite As New HtmlTextWriter(strWrite)
            Dim htmfrm As New HtmlForm()
            grEmp.AllowPaging = False
            htmfrm.Attributes("runat") = "server"
        Catch ex As Exception
        End Try
    End Sub
  • Notice that I have added an overriding function VerifyRenderingInServerForm in the code behind. This is to resolve the error “Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server” that may occur on exporting GridView data to MS Excel file or MS Word or PDF or CSV (Comma separated value) file.
Note: To view complete article on why this error occur and how to resolve that error, read my article “How to Solve Error Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server

  • Exported gridview data to word file will look like as shown in figure:

Bind and Export GridView data to Ms Word in
click on image to  enlarge
  Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."                             
Next Post »


Click here for comments
October 15, 2013 ×

The C#.NET GridView is able to export data to Word documents.

January 22, 2014 ×

hi the above code is fine and its working properly,My problem is to import the 3 data grid tables data to document(doc) file(when i click image button).Please let me know the code for it..,..,.


If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..