.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> Collections >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

convert datatable to csv file using c#

Posted By:Rahul       Posted Date: March 11, 2009    Points: 10    Category: Collections    URL: http://www.dotnetspark.com  
 

This function is useful to convert datatable to .csv file. This method also allows you to pass your own separate character. The code example is in C#.

Below function will accept three input datatable, FilePath and the seperateChar

///


/// This method is used to Convert DataTable to CSV ( comma seperated ) file.
///

///
///
///

public static void DataTable2CSV(DataTable table, string filename, string seperateChar)
{

StreamWriter sr = null;

try
{

sr = new StreamWriter(filename);
string seperator = "";
StringBuilder builder = new StringBuilder();
foreach (DataColumn col in table.Columns)
{

builder.Append(seperator).Append(col.ColumnName);

seperator = seperateChar;
}

sr.WriteLine(builder.ToString());

foreach (DataRow row in table.Rows)
{

seperator = "";
builder =
new StringBuilder();
foreach (DataColumn col in table.Columns)
{

builder.Append(seperator).Append(row[col.ColumnName]);
seperator = seperateChar;

}

sr.WriteLine(builder.ToString());

}

}

finally
{

if (sr != null)
{

sr.Close();

}

}

}



     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend