Friday, February 27, 2015

GridView Export To Word ASP.NET & C#

In this article we will see how to export grid-view to excel or word.

Step 1 : Create a new database in SQL server or if you have a database already go to step 2.

CREATE DATABASE (YOUR DATABASE NAME);

Step 2 : Create a table in the database.

CREATE TABLE Employee
(
    EmployeeID INT,
    Name Varchar(250),
    Salary Decimal (10,2)

);

Step 3 : Insert some sample data to the table.

INSERT INTO Employee VALUES (1,'Scott',1000);
INSERT INTO Employee VALUES (2,'John',1100);
INSERT INTO Employee VALUES (3,'Phil',1200);
INSERT INTO Employee VALUES (4,'Peter',1300);
INSERT INTO Employee VALUES (5,'Jose',1400);

INSERT INTO Employee VALUES (6,'Morgan',1500);


Step 4 : Now Add a WebForm to your Project and add the GridView Control and Button to Export the Data.


 <asp:GridView ID="GridView1" runat="server"></asp:GridView>
 <asp:Button ID="btnExportWord" runat="server" Text="Export To Word" OnClick="btnExportWord_Click" />

Step 5 : Add the following code to your Page.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridView();
            }
        }

        private void BindGridView()
        {
            string connectionString = "Data Source=.SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True";
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "SELECT * FROM Employee";
                cmd.Connection = con;
                con.Open();

                SqlDataReader dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);

                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

        private void ExportGridView(string fileName, string contentType)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
            Response.Charset = "";
            Response.ContentType = contentType;

            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            GridView1.RenderControl(hw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.Close();
            Response.End();
        }

    protected void btnExportWord_Click(object sender, EventArgs e)
    {
            ExportGridView("GridData.doc", "application/vnd.ms-word");
     }

        public override void VerifyRenderingInServerForm(Control control)
        {
            
        }

No comments:

Post a Comment