Gridview export to CSV
In this lesson we are going to export GridView data to a .CSV file.
Default.aspx page code:-
Default.aspx.cs page code:-
Output:-
Default.aspx page code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
Default.aspx.cs page code:-
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; using System.Text; public partial class Default3 : System.Web.UI.Page { string connectionString = "Data Source=PS-PC\\SANTOSH;Initial Catalog=dbSantoshTest;Integrated Security=True"; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { loadRecord(); } } protected void loadRecord() { SqlConnection con = new SqlConnection(connectionString); con.Open(); SqlCommand cmd = new SqlCommand("Select * from tblRecord", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); int count = ds.Tables[0].Rows.Count; con.Close(); if (ds.Tables[0].Rows.Count > 0) { Gridview1.DataSource = ds; Gridview1.DataBind(); } else { ds.Tables[0].Rows.Add(ds.Tables[0].NewRow()); Gridview1.DataSource = ds; Gridview1.DataBind(); int columncount = Gridview1.Rows[0].Cells.Count; } } public override void VerifyRenderingInServerForm(Control control) { /*Tell the compiler that the control is rendered * explicitly by overriding the VerifyRenderingInServerForm event.*/ } protected void btnExportCSV_Click(object sender, EventArgs e) { Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=gvtocsv.csv"); Response.Charset = ""; Response.ContentType = "application/text"; StringBuilder sBuilder = new System.Text.StringBuilder(); for (int index = 0; index < Gridview1.Columns.Count; index++) { sBuilder.Append(Gridview1.Columns[index].HeaderText + ','); } sBuilder.Append("\r\n"); for (int i = 0; i < Gridview1.Rows.Count; i++) { for (int k = 0; k < Gridview1.HeaderRow.Cells.Count; k++) { sBuilder.Append(Gridview1.Rows[i].Cells[k].Text.Replace(",", "") + ","); } sBuilder.Append("\r\n"); } Response.Output.Write(sBuilder.ToString()); Response.Flush(); Response.End(); } }
Output:-