How To Export GridView to Excel

Excel is a compelling application from Microsoft. Excel helps businesses analyze the data, like producing graphs and charts and storing and sorting data.

This article will show you how to export ASP.NET GridView data to Excel using C#. The code is straightforward and easy to understand.

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

<!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>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="server" BackColor="LightGoldenrodYellow" BorderColor="Tan"
               BorderWidth="1px" CellPadding="2" Font-Names="Tahoma" ForeColor="Black" GridLines="None"
               Width="300px"  AutoGenerateColumns="False">
               <FooterStyle BackColor="Tan" />
               <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
               <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
               <HeaderStyle BackColor="Tan" Font-Bold="True" />
               <AlternatingRowStyle BackColor="PaleGoldenrod" />
               <Columns>
                   <asp:BoundField DataField="Id" Visible="False" />
                   <asp:BoundField DataField="Name" HeaderText="Name">
                       <HeaderStyle HorizontalAlign="Left" />
                   </asp:BoundField>
                   <asp:BoundField DataField="Description" HeaderText="Description">
                       <HeaderStyle HorizontalAlign="Left" />
                   </asp:BoundField>
               </Columns>
           </asp:GridView>
           <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Export To Excel" /></div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.IO;

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

        }

    }
    private void BuildUserList()
    {
        IList<User> users = new List<User>();
        users.Add(new User("Xyz", "Coder"));
        users.Add(new User("Abc", "Writer"));
        users.Add(new User("Charles", "Poet"));

        // assign users to GridView
        GridView1.DataSource = users;
        GridView1.DataBind();
    }
    public class User
    {

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="name"></param>
        /// <param name="description"></param>
        public User(string name, string description)
        {
            _name = name;
            _description = description;
            _id = Guid.NewGuid().ToString();
        }

        private string _id;

        public string Id
        {
            get { return _id; }
            set { _id = value; }
        }

        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private string _description;

        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
        Response.Charset = "";
        // If you want the option to open the Excel file without saving than
        // comment out the line below
        // Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.xls";
        StringWriter stringWrite = new System.IO.StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {

        // Confirms that an HtmlForm control is rendered for the
        //specified ASP.NET server control at run time.
        //for more details check out this link
        //http://msdn.microsoft.com/en-us/library/system.web.ui.page.verifyrenderinginserverform.aspx

        GridView grid = control as GridView;
        if (grid != null && grid.ID == "GridView1")
            return;
        else
            base.VerifyRenderingInServerForm(control);
    }
}

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم