C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » C# Syntax »

Create csv file from DataTable


Posted Date: 04 May 2009    Resource Type: Code Snippets    Category: C# Syntax
Author: Lakhan PalMember Level: Diamond    
Rating: 1 out of 5Points: 2



Create a file "Data.csv". now iterate the data of DataTable and write on the file using stream writer.


// Create the CSV file to which dataTable will be exported.
StreamWriter sw = new StreamWriter(Server.MapPath("~/Data.csv"), false);
// First we will write the headers.
DataTable dt = {Get Data From Database};
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();



Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Export  .  DataTable  .  Csv  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Removes unnecesary SPOpjects from the Manifest.xml file in SharePoint
Previous Resource: Read content of Text File
Return to Discussion Resource Index
Post New Resource
Category: C# Syntax


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use