connectseekers.com

Thursday, 24 July 2014

GridView Export to Word Document (.doc/.docx) in Asp.Net Using C#.Net

7/24/2014 - By Pranav Singh 0

This article will show you how you can export the gridview in word document (.doc or .docx) in asp.net using c#.net.

So for this article first we will create a new asp.net application and add the below code in  .aspx page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DocExport.aspx.cs" Inherits="ProjectDemo_Asp.et.PDFExport" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title> GridView Export to Word Document(.doc/.docx) in Asp.Net Using C#.Net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            BorderStyle="Solid" EmptyDataText="There are no data records to display.">
            <Columns>
                <asp:BoundField DataField="author_name" HeaderText="NAME" />
                <asp:BoundField DataField="publisher_name" HeaderText="PUBLISHER NAME" />
                <asp:BoundField DataField="publication_year" HeaderText="PUBLISH YEAR" />
                <asp:BoundField DataField="retail_price" HeaderText="PRICE" />
            </Columns>
            <HeaderStyle BackColor="#66CCFF" />
        </asp:GridView>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="Export To DOC" />
   
    </div>
    </form>
</body>
</html>

Now let’s come to code part of the page. In this first we will bind the grid view and then we will write code to export the gridview to the ms word document.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.HtmlControls;
namespace ProjectDemo_Asp.et
{
    public partial class PDFExport : System.Web.UI.Page
    {
        public string connectionstring = "<---your --="" connection="" string="">";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable _objdt = new DataTable();
                _objdt = GetDataFromDataBase();
                if (_objdt.Rows.Count > 0)
                {
                    GridView1.DataSource = _objdt;
                    GridView1.DataBind();
                }
            }
        }

        ///
        /// Function for binding retrieving the data from database
        ///
        public DataTable GetDataFromDataBase()
        {
            DataTable _objdt = new DataTable();
            string querystring = "select * from Books;";
            SqlConnection _objcon = new SqlConnection(connectionstring);
            SqlDataAdapter _objda = new SqlDataAdapter(querystring, _objcon);
            _objcon.Open();
            _objda.Fill(_objdt);
            return _objdt;
        }
        ///
        /// Click event to export the grivview data into pdf format
        ///

        ///
        ///
        protected void Button1_Click(object sender, EventArgs e)
        {
            HtmlForm _objhtmlform = new HtmlForm();
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "";
            Response.AddHeader("content-disposition"string.Format("attachment;filename={0}""bookdetail.doc"));
            Response.ContentType = "application/ms-msword";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            GridView1.AllowPaging = false;
            /*Retrive and bind data to gridview*/
            DataTable _objdt = new DataTable();
            _objdt = GetDataFromDataBase();
            if (_objdt.Rows.Count > 0)
            {
                GridView1.DataSource = _objdt;
                GridView1.DataBind();
            }
            _objhtmlform.Attributes["runat"] = "server";
            _objhtmlform.Controls.Add(GridView1);
            this.Controls.Add(_objhtmlform);
            _objhtmlform.RenderControl(hw);
            string strstyle = @"";
            Response.Write(strstyle);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */

        }
    }
}

       

You will notice I have added a blank function names as VerifyRenderingInServerForm. If we will not add this function on that case we will not able to export the document. We will get error. You will get error that gridview is not placed in server tag.

        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */

        }

Now we will run the application to view the output.


Now click on export to doc and you will get the output as shown below.


DOWNLOAD

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com
Email Id : contact@aspdotnet-pools.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Top jQuery Plugins

Global Classified : Connectseekers.com
© 2014
back to top