Tuesday, June 2, 2009

Export C#.Net DataSet to a CSV File

You can export a Data set to a CSV file in C#.Net. The following method get Path to CSV file and DataSet as parameters and create the CSV file in given path.

public static void ExportGridView(string Path, DataSet ds)
{
StreamWriter sw = new StreamWriter(Path);
DataTable dt = ds.Tables[0];
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();
}

No comments:

Post a Comment