How to Export GridView data to Ms-Word in Asp.Net

← Prev

You can use the DataGrid control in Asp.Net to export GridView data to an Ms-Word document. I am sharing codes here, both C# and Vb.Net, which explains how easily you can export data extracted from a paging enabled GridView to an Ms-Word doc file.

Export GridView to Ms-Word in Asp.Net

Related Post: How to Import data from Ms-Word table to a GridView Control

Let us see the example.

The Markup

First, add a GridView control on your web page and populate data to the grid using SqlDataSource.

<div>
    <!--Add a GridView Control.-->
    <asp:GridView
        ID="grdBooks" 
        runat="server" 
        AutoGenerateColumns="False" 
        DataKeyNames="BookID" 
        DataSourceID="SqlDataSource1" 
        AllowPaging="true" 
        PageSize="5">

    <Columns>
        <asp:BoundField DataField="BookID" HeaderText="BookID" InsertVisible="False" 
            ReadOnly="True" SortExpression="BookID" />
        <asp:BoundField DataField="BookName" HeaderText="BookName" 
            SortExpression="BookName" />
        <asp:BoundField DataField="Category" HeaderText="Category" 
            SortExpression="Category" />
        <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />
    </Columns>
    </asp:GridView>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ENCODEDNAConnectionString2 %>" 
                    
        SelectCommand="SELECT [BookID], [BookName], [Category], [Price] FROM [Books]">
    </asp:SqlDataSource>

    <div>
    <input type="button" id="btExport" value="Export data To Word File" 
        onserverclick="ExportToWord" runat="server" />
    </div>
</div>

Along with the GridView, I have also added a button, and its server click event will call a code behind function to export the GridView data.

Code behind (C#)
using System;
using System.Data;                     // For database.
using System.Data.SqlClient;           // For SQL Connection.
using System.Web.UI.WebControls;       // For DataGrid.

public partial class SiteMaster : System.Web.UI.MasterPage
{
    System.Data.DataTable mytable = new System.Data.DataTable();
    System.Data.DataRow dr = null;

    protected void ExportToWord(object sender, EventArgs e)
    {
        Create_DataTable();         // Create a DataTable.

        // Calculate grand total.
        Decimal dTotalPrice = 0;
        for (int i = 0; i <= mytable.Rows.Count - 1; i++)
        {
            dTotalPrice += mytable.Rows[i].Field<Decimal>(3);
        }

        // Now, assign data to a DataGrid.
        DataGrid dg = new DataGrid();
        dg.DataSource = mytable;
        dg.DataBind();

        // Ms-Word file.
        string sFileName = "Books - " + System.DateTime.Now.Date + ".doc";
        sFileName = sFileName.Replace("/", "");

        // Send ouput to the client machine using the "Response" object.
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=" + sFileName);
        Response.ContentType = "application/vnd.ms-word";
        EnableViewState = false;

        System.IO.StringWriter objSW = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter objHTW = new System.Web.UI.HtmlTextWriter(objSW);

        dg.HeaderStyle.Font.Bold = true;     // Set the header as bold.
        dg.RenderControl(objHTW);

        // Add style to the Table.
        Response.Write("<style> TABLE { font: 17px Calibri; border:dotted 1px #999; } " +
                "td { border:dotted 1px #3d3d3d; text-align:center; padding: 2px 5px; } </style>");
        Response.Write(objSW.ToString());

        // Add a row at the end of the doc file showing Price grand total.
        Response.Write("<tr><td><b>Total: </b></td><b>" +
                dTotalPrice.ToString("N2") + "</b></td></tr>");

        Response.End();
        dg = null;
    }

    private void Create_DataTable()
    {
        int iRowCnt = 0;

        // Create a DataTable and add columns to it.
        mytable.Columns.Add(new System.Data.DataColumn("Book ID", System.Type.GetType("System.String")));
        mytable.Columns.Add(new System.Data.DataColumn("Name of the Book", System.Type.GetType("System.String")));
        mytable.Columns.Add(new System.Data.DataColumn("Category", System.Type.GetType("System.String")));
        mytable.Columns.Add(new System.Data.DataColumn("Price ($)", System.Type.GetType("System.Decimal")));

        // Remove paging to help export entire GridView to Word file.
        grdBooks.AllowPaging = false;
        grdBooks.DataBind();

        foreach (GridViewRow row in grdBooks.Rows)
        {
            dr = mytable.NewRow();
            dr[0] = grdBooks.Rows[iRowCnt].Cells[0].Text;
            dr[1] = grdBooks.Rows[iRowCnt].Cells[1].Text;
            dr[2] = grdBooks.Rows[iRowCnt].Cells[2].Text;
            dr[3] = grdBooks.Rows[iRowCnt].Cells[3].Text;

            mytable.Rows.Add(dr);

            iRowCnt += 1;
        }
    }
}
The function ExportToWord is called after a button click. Its where I have actual for exporting the data to a Word document. However, first I’ll extract data from the GridView and store the data in a DataTable named myTable. A DataTable is a temporary storage, which can hold table in tabular format. See procedure private void Create_DataTable().

Next, I have defined a DataGrid control and I’ll bind it with the DataTable. This is the control that is actully doing the data export.

DataGrid dg = new DataGrid();
dg.DataSource = mytable;
dg.DataBind();

I’ll use the DataGrid object to write data to the HtmlTextWriter (dg.RenderControl(objHTW);) and finally send a request to the response stream (Response.Write(objSW.ToString());).

Code behind (Vb.Net)
Option Explicit On
Imports System.Data                 ' For database.
Imports System.Data.SqlClient       ' For SQL Connection.

Partial Class Site
    Inherits System.Web.UI.MasterPage

    Dim mytable As New Data.DataTable()
    Dim row As Data.DataRow

    Protected Sub ExportToWord(ByVal sender As Object, ByVal e As EventArgs)
        Call Create_DataTable()         ' Create a DataTable.

        Dim dTotalPrice As Double = 0

        ' Calculate grand total.
        For i = 0 To mytable.Rows.Count - 1
            dTotalPrice += mytable.Rows(i).Item("Price ($)")
        Next

        ' Now, assign data to a DataGrid.
        Dim dg As New DataGrid
        dg.DataSource = mytable : dg.DataBind()

        ' Ms-Word file.
        Dim sFileName As String = "Books - " & Replace(Date.Now.Date, "/", "") & ".doc"

        ' Send ouput to the client machine using the "Response" object.
        Response.ClearContent()
        Response.Buffer = True
        Response.AddHeader("content-disposition", "attachment; filename=" & sFileName)
        Response.ContentType = "application/vnd.ms-word"
        Me.EnableViewState = False

        Dim objSW As New System.IO.StringWriter
        Dim objHTW As New HtmlTextWriter(objSW)

        dg.HeaderStyle.Font.Bold = True     ' Set the header as bold.
        dg.RenderControl(objHTW)

        ' Add style to the Table.
        Response.Write("<style> table { font: 17px Calibri; border:dotted 1px #999; } " & _
            "td { border: dotted 1px #3d3d3d; text-align:center; padding: 2px 5px; } </style>")

        Response.Write(objSW.ToString())

        ' Add a row at the end of the doc file showing Price grand total.
        Response.Write("<tr><td><b>Total Price: </b></td><b>" & _
            Decimal.Parse(dTotalPrice).ToString("N2") & "</b></td></tr>")

        Response.End()
        dg = Nothing
    End Sub

    Private Sub Create_DataTable()
        Dim iRowCnt As Integer = 0

        ' Create a DataTable and add columns to it.
        mytable.Columns.Add(New Data.DataColumn("Book ID", System.Type.GetType("System.String")))
        mytable.Columns.Add(New Data.DataColumn("Name of the Book", System.Type.GetType("System.String")))
        mytable.Columns.Add(New Data.DataColumn("Category", System.Type.GetType("System.String")))
        mytable.Columns.Add(New Data.DataColumn("Price ($)", System.Type.GetType("System.String")))

        ' Remove paging to help export entire GridView to Word file.
        grdBooks.AllowPaging = False
        grdBooks.DataBind()

        ' Populate DataTable using GridView row values.
        For Each GridViewRow In grdBooks.Rows
            row = mytable.NewRow
            row(0) = grdBooks.Rows(iRowCnt).Cells(0).Text
            row(1) = grdBooks.Rows(iRowCnt).Cells(1).Text
            row(2) = grdBooks.Rows(iRowCnt).Cells(2).Text
            row(3) = grdBooks.Rows(iRowCnt).Cells(3).Text

            mytable.Rows.Add(row)

            iRowCnt += 1
        Next
    End Sub
End Class
Conclusion

This is one of the simplest ways to export GridView data to an Ms-Word document. Here, I am not exporting GridView data directly to the Word document. The control, which actually does this, is the DataGrid control. No just Word doc, using the same technique you can Export GridView data to an Excel worksheet.

Thanks for reading.

← Previous


Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.
Delivered by FeedBurner