Sunday, May 12, 2013

how to export gridview to csv file in asp.net

Title: How to export grid view data to CSV or Text file in asp.net using c#.net

Description:
As per previous articles we have seen how to Bind CSV data to Grid view in asp.net,Export Grid view Data to Word Document,Export Grid view data to PDF document,Import XML data to GridView in Asp.net .Here i would like explain about how to export grid view data to CSV file in asp.net.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Export2CSV.aspx.cs" Inherits="Export2CSV" EnableEventValidation="false" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GvOrderDetails" runat="server" AutoGenerateColumns="False" >
</asp:GridView>
<asp:Button ID="btnExportCSV" runat="server" Text="Gridview To CSV" onclick="btnExportCSV_Click" />
<div>
</div>
</form>
</body>
</html>
Code behind:In the below Grid view data bind has done while page loading.when we fire click event the data colud be export to CSV file
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.SqlClient;
using System.Data;
using System.Configuration;


public partial class Export2CSV : System.Web.UI.Page
{
SqlConnection Econ = new SqlConnection(ConfigurationManager.ConnectionStrings["Exportconn"].ToString());
DataSet ds = new DataSet();
  
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlCommand cmd = new SqlCommand("select * from orders", Econ);
SqlDataAdapter Gda = new SqlDataAdapter(cmd);
Gda.Fill(ds);
GvOrderDetails.DataSource = ds;
GvOrderDetails.DataBind();
}
}

protected void btnExportCSV_Click(object sender, EventArgs e)
{
     
SqlDataAdapter Cda = new SqlDataAdapter("SELECT* FROM Orders",Econ);
DataTable Gdt = new DataTable();
Cda.Fill(ds);
    //Bind data to Data table
Gdt = ds.Tables[0];
StreamWriter Exportsw = new StreamWriter("E:\\OrderCSVReport.csv", false);
int CSVCount = Gdt.Columns.Count;
for (int i = 0; i < CSVCount; i++)
{
Exportsw.Write(Gdt.Columns[i]);
if (i < CSVCount - 1)
{
Exportsw.Write(",");
}
}
Exportsw.Write(Environment.NewLine);

foreach (DataRow Gdr in Gdt.Rows)
{
for (int i = 0; i < CSVCount; i++)
{
if (!Convert.IsDBNull(Gdr[i]))
{
Exportsw.Write(Gdr[i].ToString());
}
if (i < CSVCount - 1)
{
Exportsw.Write(",");
}
}
Exportsw.Write(Environment.NewLine);
}
Exportsw.Close();
}
}
}

Post a Comment

Bel