connectseekers.com

Tuesday, 29 July 2014

GridView Export to CSV in Asp.Net Using C#.Net and VB.Net

7/29/2014 - By Pranav Singh 0

This article will show you how you can export the gridview into CSV file. In this article I have used asp.net, c#.net for exporting gridview bind to sql database table into CSV by comma(,).


So for this article we will first create a new asp.net application. Add a gridview into it. After adding this we will add a button control. So here is the html code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CSVExport.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 CSV in Asp.Net Using C#.Net and VB.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 CSV" />
   
    </div>
    </form>
</body>
</html>

Now add the below code into the .cs file.

using System;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Text;
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)
            {
                /*Data to display on screen*/
                DataTable _objdt = new DataTable();
                _objdt = GetDataFromDataBase();
                if (_objdt.Rows.Count > 0)
                {
                    GridView1.DataSource = _objdt;
                    GridView1.DataBind();
                }
            }
        }

        ///

        /// Function for binding retribing 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 CSV format
        ///

        ///
        ///
        protected void Button1_Click(object sender, EventArgs e)
        {
            /*Data to bind to gridview and then export to CSV*/
            DataTable _objdt = new DataTable();
            _objdt = GetDataFromDataBase();
            if (_objdt.Rows.Count > 0)
            {
                GridView1.DataSource = _objdt;
                GridView1.DataBind();
            }
            Response.Clear();
            Response.Buffer = true;
            /*Provide the CSV File name*/
            Response.AddHeader("content-disposition""attachment;filename=BookDetail.csv");
            Response.Charset = "";
            Response.ContentType = "application/text";
            GridView1.AllowPaging = false;
            GridView1.DataBind();
            StringBuilder _objstr = new StringBuilder();
            for (int k = 0; k < GridView1.Columns.Count; k++)
            {
                /*Add separator to header value*/
                _objstr.Append(GridView1.Columns[k].HeaderText + ',');
            }
            /*Append all the rows of the gridview*/
            _objstr.Append("\r\n");
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                for (int k = 0; k < GridView1.Columns.Count; k++)
                {
                    /*Add separator to row value*/
                    _objstr.Append(GridView1.Rows[i].Cells[k].Text + ',');
                }
                /*Add separator to row value*/
                _objstr.Append("\r\n");
            }
            /*For output file*/
            Response.Output.Write(_objstr.ToString());
            Response.Flush();
            Response.End();
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
   
          
        }
    }
}

       

In above code first I have bind the table data to gridview and then on button click event I have added the export code to csv. The above code will generate the comma separated csv file.

Now run the page and click on export button.



Now click on export button and open it with excel


Now open it with notepad the check the output.


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