Export GridView selected rows to Excel or word in ASP.NET using CSharp

Category > ASP.NET || Published on : Tuesday, February 9, 2016 || Views: 9890 || Export GridView selected rows to Excel or word in ASP.NET using CSharp Export GridView selected rows GridView selected rows to Excel GridView selected rows to Word


Introduction

Here Pawan Kumar will explain how to Export GridView selected rows to Excel or word in ASP.NET using CSharp

Description

In previous post I have explained jQuery to Check UnCheck All CheckBoxes in Repeater in Asp.Net C#, Check UnCheck All CheckBoxes in Asp.Net GridView using jQuery, Asp.Net Serialization & Deserialization with C#.Net, jQuery to Dynamically Change or Set Placeholder Text in Asp.Net TextBox, jQuery to Validate File Type and Size before Uploading through Asp.Net FileUpload Control, How to clear the file upload control value using jQuery / JavaScript, and many more articles.

Now I will explain How to Export GridView selected rows to Excel or word in ASP.NET using CSharp

So follow the steps to learn Export GridView selected rows to Excel or word in ASP.NET using CSharp

Step 1: Create a database with name "Test". After that also create a table with following structure

 CREATE TABLE [dbo].[User_Details](
     [Username] [nvarchar](100) NULL,    
     [USER_ID] [int] IDENTITY(1,1) NOT NULL,
     [Gender] [varchar](15) NULL,
     [Country] [varchar](50) NULL   
)

Step 2: Create a new website using Visual Studio 2010.

Step 3: Add a new page to the website(default.aspx) and write the following codes:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Export GridView selected rows to Excel or word in ASP.NET</title>
    <style type="text/css">
        .btn {
            width: 150px;
            padding: 2px 5px;
            font-weight: bold;
            font-size: 13px;
            font-family: Tahoma, Arial;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>
                        <asp:GridView ID="GridData" runat="server" BackColor="White" BorderColor="#CC9966"
                            BorderStyle="Solid" AutoGenerateColumns="False" BorderWidth="1px" CellPadding="4"
                            Font-Names="Georgia" DataKeyNames="User_ID" Font-Size="Small">
                            <Columns>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:CheckBox ID="chkSelect" runat="server" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField DataField="User_ID" HeaderText="User_ID" SortExpression="User_ID" />
                                <asp:BoundField DataField="UserName" HeaderText="User Name" SortExpression="UserName" />
                                <asp:BoundField DataField="Gender" HeaderText="Gender" SortExpression="Gender" />
                                <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
                            </Columns>
                            <FooterStyle BackColor="Tan" />
                            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                        </asp:GridView>
                    </td>
                    <td>
                        

                        <asp:Button ID="btnExportToExcel" runat="server" Text="Export To Excel" CssClass="btn"
                            OnClick="btnExportToExcel_Click"></asp:Button><br />
                        <br />
                        <asp:Button ID="btnExportToWord" runat="server" Text="Export To Word" CssClass="btn"
                            OnClick="btnExportToWord_Click"></asp:Button><br />
                        <br />
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

Step 4: After, Write the following codes to code behind file of default.apx

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
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;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridData();
        }
    }

    private void BindGridData()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        SqlCommand cmd = new SqlCommand("select * from User_Details ORDER BY USER_ID ASC", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        ViewState["ds"] = ds;
        GridData.DataSource = ds;
        GridData.DataBind();
    }

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

    protected void GridData_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        CheckedRecordsData();
        GridData.PageIndex = e.NewPageIndex;
        BindGridData();
    }

    private void ExportSelectedData(string header, string contentType)
    {
        CheckedRecordsData();
        Response.ClearContent();
        Response.AddHeader("content-disposition", header);
        Response.ContentType = contentType;
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        if (ViewState["Checked_records"] != null)
        {
            ArrayList CheckBoxArray = (ArrayList)ViewState["Checked_records"];

            for (int i = 0; i < GridData.Rows.Count; i++)
            {
                GridViewRow row = GridData.Rows[i];
                row.Visible = false;
                int index = (int)GridData.DataKeys[row.RowIndex].Value;
                if (CheckBoxArray.Contains(index))
                {
                    row.Visible = true;
                    row.Cells[0].Visible = false;
                }
                else
                {
                    row.Visible = false;
                    row.Cells[0].Visible = true;
                }
            }
        }
        GridData.RenderControl(hw);
        Response.Output.Write(sw.ToString());
        Response.End();
    }

    private void CheckedRecordsData()
    {
        ArrayList userdetails = new ArrayList();
        int rowindex = -1;
        foreach (GridViewRow row in GridData.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                rowindex = (int)GridData.DataKeys[row.RowIndex].Value;
                bool result = (row.FindControl("chkSelect") as CheckBox).Checked;

                if (ViewState["Checked_records"] != null)
                    userdetails = (ArrayList)ViewState["Checked_records"];
                if (result)
                {
                    if (!userdetails.Contains(rowindex))
                        userdetails.Add(rowindex);
                }
                else
                    userdetails.Remove(rowindex);
            }
        }

        // if (userdetails != null && userdetails.Count > 0)
        ViewState["Checked_records"] = userdetails;
    }

    protected void btnExportToExcel_Click(object sender, EventArgs e)
    {
        ExportSelectedData("attachment;filename=GridViewExport.xls", "application/vnd.ms-excel");

    }

    protected void btnExportToWord_Click(object sender, EventArgs e)
    {
        ExportSelectedData("attachment;filename=GridViewExport.doc", "application/vnd.ms-word");

    }
}

Screenshot:-

Conclusion:

So, In this tutorial we have learned, Export GridView selected rows to Excel or word in ASP.NET using CSharp

Download Source Codes