Export datatable to CSV in C#.net


How to export data from datatable to CSV, you will find the code for exporting data from datatable to CSV.

Export data from datatable to CSV


We will guide you on how to export data from datatable to CSV, please find its detail.


public void CreateCSVFile(DataTable dt, string strFilePath)
{
StreamWriter sw = new StreamWriter(strFilePath, false);
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);
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();
}


Comments

Author: sathyanarayanan20 Mar 2012 Member Level: Gold   Points : 1

hai
successfully exported...but.. i have address column...if i stored 23,delhi road in address column means,in csv 23 is display in address column,delhi road is display in next column...i want display 23,delhi road in address column in csv...how to correct it...plz help...

Guest Author: anamika27 Nov 2012

use escape character for ,(coma) in address field, before writing the data to stream writer.

Author: Gustavo Simone15 Jul 2016 Member Level: Bronze   Points : 2

There's a DLL library called DataTableToPDF from GusimoSoft (http://www.gusimosoft.tk) that can export a DataTable to a complete PDF report and even include a logo, title, totals, exclude columns, etc. It's very cool.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: