Generating a Comma-Delimited File from a DataSet
This is a pretty simple block of code. There are other ways to export a CDF, this works for me.
<%@ page language="C#" enableviewstate="false" %>
<%@ import namespace="System.Data" %>
<%@ import namespace="System.Data.SqlClient" %>
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
String strSelected = Request.QueryString["ID"];
DataSet dstClientList =
MyNameSpace.Customers.GetCustomers(strSelected );
DataTable dt = dstClientList.Tables[0];
System.Text.StringBuilder sbHead = new System.Text.StringBuilder();
System.Text.StringBuilder sbBody = new System.Text.StringBuilder();
Object[] columns;
// Write the Column Names
foreach (DataColumn dc in dt.Columns)
{
sbHead.Append(dc.ColumnName);
sbHead.Append(",");
}
if (sbHead.Length > 0) sbHead.Remove(0,1).Append("\r\n");
// Write the Data Rows
foreach (DataRow dr in dt.Rows)
{
columns = dr.ItemArray;
foreach (Object column in columns)
{
sbBody.Append(column.ToString());
sbBody.Append(",");
}
if (sbBody.Length > 0) sbBody.Remove(sbBody.Length - 1, 1)._
Append("\r\n");
}
Response.Clear ();
Response.Buffer = true;
Response.ContentType = "text/plain";
Response.AddHeader ("Content-Disposition", _
"inline;filename=cdf.txt");
this.EnableViewState = false;
Response.Write(sbHead.ToString());
Response.Write(sbBody.ToString());
Response.End ();
} </script>
Get the above in a block that's easy to cut and paste (MSIE users should right-click and use Save Target As...), it also contains the improvements suggested in the comments. Enjoy!