Hi friends,
export datatable to csv c# asp.net ?
Please help me on this...
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Manoj BhoirPosted May 8, 2015, 3:56 AM
you can write your own extension method to export Datatable to CSV.
Please see this code :
public static void ToCSV(this DataTable dtDataTable, string strFilePath)
{
StreamWriter sw = new StreamWriter(strFilePath, false);
//headers
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
sw.Write(dtDataTable.Columns[i]);
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dtDataTable.Rows)
{
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string value = dr[i].ToString();
if (value.Contains(','))
{
value = String.Format("\"{0}\"", value);
sw.Write(value);
}
else
{
sw.Write(dr[i].ToString());
}
}
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
Or simplest way :
StringBuilder sb = new StringBuilder();
string[] columnNames = dt.Columns.Cast
Select(column => column.ColumnName).
ToArray();
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
string[] fields = row.ItemArray.Select(field => field.ToString()).
ToArray();
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText("test.csv", sb.ToString());
For more details please check these links :
Export Datatable to CSV Using Extension Method
http://www.c-sharpcorner.com/UploadFile/deveshomar/export-datatable-to-csv-using-extension-method/
http://stackoverflow.com/questions/4959722/c-sharp-datatable-to-csv
http://www.codeproject.com/Tips/665519/Writing-a-DataTable-to-a-CSV-file
http://www.codeproject.com/Tips/591034/Simplest-code-to-export-a-datatable-into-csv-forma