Posted by: R Manimaran | September 26, 2008

Convert DataTable to CSV File

Get the DataTable from Sql
private DataTable GetQueryOutput(string Sql)
{
DataTable dtResult = null;
if (con.State != ConnectionState.Open)
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(Sql, con);
dtResult = new DataTable(“Output”);
dtResult.BeginLoadData();
da.Fill(dtResult);
dtResult.EndLoadData();
return dtResult;
}

//Declare a StreamWriter
System.IO.StreamWriter writer=null;
string SepChar=”,”;
try
{
writer = new StreamWriter(FileName);
string sep = “”;
StringBuilder builder = new StringBuilder();
string Sql=string.Empty;
//Writing the Column Heading
foreach (DataColumn col in dt.Columns)
{
builder.Append(sep).Append(col.ColumnName);
sep = SepChar;
}
writer.WriteLine(builder.ToString());

//write the Rows
foreach (DataRow row in dt.Rows)
{
sep = “”;
builder = new StringBuilder();
foreach (DataColumn col in dt.Columns)
{
builder.Append(sep).Append(row[col.ColumnName]);
sep = SepChar;
}
writer.WriteLine(builder.ToString());

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: