ASP.NET GridView Data Export to Excel with Custom Styling

Introduction

In the dynamic realm of web development, providing users with efficient data export features enhances the overall user experience. This article explores how to create a visually appealing ASP.NET GridView and seamlessly export its data to an Excel file. We'll delve into the HTML markup, CSS styling, and C# coding needed to achieve this functionality.

 how to export gridview data to excel

HTML Markup: Designing the Page

The HTML markup lays the foundation for our GridView. It includes a GridView control populated with sample book data and a button triggering the export functionality. The styling classes are set to enhance the visual appeal of the GridView.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView" %>
<!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></title>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            HeaderStyle-CssClass="HeaderStyle" >
            <Columns>
                <asp:BoundField DataField="Book_Id" HeaderText="Book Id" 
                    SortExpression="Book_Id" />
                <asp:BoundField DataField="Book_name" HeaderText="Book Name" 
                    SortExpression="Book_name" />
                <asp:BoundField DataField="Book_author" HeaderText="Book Author" 
                    SortExpression="Book_author" />
                <asp:BoundField DataField="Book_Publisher_name" 
                    HeaderText="Book Publisher Name" SortExpression="Book_Publisher_name" />
                <asp:BoundField DataField="Book_Published_date" 
                    HeaderText="Book Published Date" SortExpression="Book_Published_date" />
            </Columns>            
        </asp:GridView>
        <br />
        <asp:Button ID="Btn_Export" runat="server" Text="Export to Excel" 
            onclick="Btn_Export_Click" />
    </div>
    </form>
</body>
</html>

CSS Code: Enhancing Visuals

The CSS code defines styles for the GridView, including background colors and padding for better readability.


<style type="text/css">
    #GridView1
     {
        background:#fafafa;               
     }
    #GridView1 .HeaderStyle
     {
         background-color:#0066cc;   
       color:#ffffff;
       padding:7px 10px 7px 10px;
     }
    #GridView1 th
     {
        padding:10px 15px 10px 15px;
     }
    #GridView1 td
     {
        padding:5px 10px 5px 10px;
        text-align:left;
     }    
   </style>

C# Coding: Server-Side Logic

The C# code handles server-side logic, including connecting to the database, binding data to the GridView, and exporting the GridView data to an Excel file upon button click.


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

public partial class GridView : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["bookcon"].ConnectionString);

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

    public void FillGridView()
    {
        DataSet ds = new DataSet();
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter("Select * from Book", con);
        con.Close();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    
    protected void Btn_Export_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.AppendHeader("content-disposition", "attachment; filename=Export_Gridview_to_Excel.xls");
        Response.ContentType = "application/excel";
        StringWriter stringwrite = new StringWriter();
        Html32TextWriter htmltextwriter = new Html32TextWriter(stringwrite);        
        GridView1.HeaderRow.Style.Add("background-color", "#0066cc");
        foreach (TableCell tbcell in GridView1.HeaderRow.Cells)
        {
            tbcell.Style["background-color"] = "#0066cc";
            tbcell.Style["color"] = "#ffffff";
            tbcell.Style["padding"] = "7px 15px 7px 15px";
        }
        foreach (GridViewRow gdrow in GridView1.Rows)
        {
            gdrow.BackColor = System.Drawing.Color.White;
            foreach (TableCell gdrowrbcell in gdrow.Cells)
            {
                gdrowrbcell.Style["background-color"] = "#ffffff";
            }
        }
        GridView1.RenderControl(htmltextwriter);
        Response.Write(stringwrite);
        Response.End();
    }
}

Conclusion

In conclusion, this article demonstrates how to create a feature-rich ASP.NET GridView with a polished export-to-Excel functionality. By combining HTML, CSS, and C# coding, developers can enhance both the visual appeal and functionality of their web applications. This streamlined approach ensures a seamless and visually pleasing experience for end-users dealing with tabular data.

Post a Comment

5 Comments

  1. @piyush : its working for me right now..... try did u get any error

    ReplyDelete
  2. RegisterForEventValidation can only be called during Render();

    I am getting this error

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. The solution is quite simple you need to notify ASP.Net that not to validate the event by setting the EnableEventValidation flag to FALSE.

      You can set it in the Web.Config in the following way

      < pages enableEventValidation ="false" >< /pages >



      This will apply to all the pages in your website. Else you can also set it in the @Page Directive of the page on which you are experiencing the above error.

      < %@ Page Language="C#" AutoEventWireup="true" EnableEventValidation = "false"

      Delete