Here is some code I used to output a CSV file for my db. It’s not commented and you’ll obviously have to alter it for your database. Please reply / email with any questions.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Stat_GetCDF : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/csv";
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString);
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT [Name], [Question], [Choices] FROM [STAT_Fields] WHERE ([SID] = '" + Request.QueryString["SID"] + "') ORDER BY [SortOrder]", con);
System.Data.SqlClient.SqlDataReader read;
con.Open();
read = cmd.ExecuteReader();
System.Collections.Generic.Dictionary<string, string> ColChoices = new System.Collections.Generic.Dictionary<string, string>();
System.Collections.Generic.Dictionary<Int32, System.Collections.Generic.Dictionary<Int32, string>> LookupValues = new System.Collections.Generic.Dictionary<int, System.Collections.Generic.Dictionary<int, string>>();
while (read.Read())
{
ColChoices.Add( "C" + read.GetString(0), read.GetString(2));
}
read.Close();
cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM [STAT_tbls_" + Request.QueryString["SID"] + "]", con);
read = cmd.ExecuteReader();
read.Read();
for (int i = 0; i < read.FieldCount; i++)
{
if (read.GetName(i) != "CID")
{
string choicesText = ColChoices[read.GetName(i)];
string[] choices = choicesText.Split(';');
System.Collections.Generic.Dictionary<Int32, string> ChoiceValues = new System.Collections.Generic.Dictionary<int, string>();
int c = 0;
foreach (string choice in choices)
{
ChoiceValues.Add(c, choice);
c++;
}
LookupValues.Add(i, ChoiceValues);
}
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < read.FieldCount; i++)
{
if (read.GetName(i) != "CID")
{
int val = read.GetInt32(i);
if (val != -1)
{
sb.Append(read.GetName(i).Substring(1));
}
if (i < (read.FieldCount - 1))
{
sb.Append(",");
}
}
}
sb.AppendLine();
while (read.Read())
{
for (int i=0; i < read.FieldCount;i++)
{
if (read.GetName(i) != "CID")
{
int val = read.GetInt32(i);
if (val != -1)
{
sb.Append(LookupValues[i][val]);
}
if (i < (read.FieldCount - 1))
{
sb.Append(",");
}
}
}
sb.AppendLine();
}
Response.Write(sb.ToString());
con.Close();
Response.End();
}
}