How to export DataTable to a csv File using C#

No.of Views3282
Bookmarked0 times
Downloads 
Votes0
By  shanaj   On  13 Apr 2010 09:04:57
Tag : CSharp , Miscellaneous
How to export DataTable to a CSV File using C#
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

 Introduction

Most of the time .NET developer asking question in message board, how to export data from DataTable to CSV or other file format.Hence i would try to give code snippet to Export data from DataTable to CSV. 

Code Snippet

public void CreateCSVFile(DataTable dt, string strFilePath)
{
try
{
// Create the CSV file to which grid data will be exported.

StreamWriter sw = new StreamWriter(strFilePath, false);

int iColCount = dt.Columns.Count;

foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount-2; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}

if (i < iColCount - 1)
{
sw.Write(",");
}

}

sw.Write(sw.NewLine);

}
sw.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

}

Note: Pass the DATATABLE  and FILEPATH + FILENAME to the above function.I used here strFilePath = FILEPATH + FILENAME. that's all, Enjoy the simple code snippets. 

Thank you

 
Sign Up to vote for this article
 
About Author
 
shanaj
Occupation-Not Provided
Company-Not Provided
Member Type-Junior
Location-Not Provided
Joined date-22 Oct 2009
Home Page-Not Provided
Blog Page-Not Provided
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top