Designer export.ascx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExportReport.aspx.cs" Inherits="Web_Crystal_Report.ExportReport" %>
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 Pagetitle>
head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" style="font-family: 'Trebuchet MS'; font-size: 10pt"
Width="100%">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
asp:GridView>
<asp:Button ID="btnExport" runat="server" onclick="btnExport_Click"
style="font-family: 'Trebuchet MS'; font-size: 10pt" Text="Export" />
form>
body>
html>
CODE BEHIND export.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Sql;
using System.Data.SqlClient;
using System.IO;
namespace Web_Crystal_Report
{
public partial class ExportReport : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection Cn = new SqlConnection("server=eingserver;database=DNN_5.2.2;uid=sa;pwd=eingtech");
SqlDataAdapter adp = new SqlDataAdapter("select * from users", Cn);
DataTable dt = new DataTable();
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnExport_Click(object sender, EventArgs e)
{
#region Export Grid to CSV
SqlConnection Cn = new SqlConnection("server=eingserver;database=DNN_5.2.2;uid=sa;pwd=eingtech");
SqlDataAdapter adp = new SqlDataAdapter("select * from users", Cn);
DataTable dt = new DataTable();
adp.Fill(dt);
StreamWriter sw = new StreamWriter("c:\\csvData.csv", false);
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
#endregion
}
}
}
Related Links
http://dotnetguts.blogspot.com/2007/01/exporting-datatable-to-csv-file-format.html