The blog has moved to a new address. The blog is now located at http://devintelligence.com

Adsense

Monday, November 27, 2006

System.Data: Export table to a CSV file

In this post I will present a function that can be used to export a data table to a CSV file. The function first loops through the columns of the data table to export the names of all the data columns. And then in next loop the code iterates over each data row to export all the values in the table.

/// <summary>
/// Exports the table to CSV string.
/// </summary>
/// <param name="table">The table.</param>
/// <param name="printHeaders">
/// if set to <c>true</c> print headers.</param>
/// <returns>CSV formated string</returns>
private static string ExportTableToCsvString(
DataTable table,
bool printHeaders
)
{
StringBuilder sb
= new StringBuilder();

if (printHeaders)
{
//write the headers.
for (int colCount = 0;
colCount
< table.Columns.Count; colCount++)
{
sb.Append(table.Columns[colCount].ColumnName);
if (colCount != table.Columns.Count - 1)
{
sb.Append(
",");
}
else
{
sb.AppendLine();
}
}
}

// Write all the rows.
for (int rowCount = 0;
rowCount
< table.Rows.Count; rowCount++)
{
for (int colCount = 0;
colCount
< table.Columns.Count; colCount++)
{
sb.Append(table.Rows[rowCount][colCount]);
if (colCount != table.Columns.Count - 1)
{
sb.Append(
",");
}
}
if (rowCount != table.Rows.Count - 1)
{
sb.AppendLine();
}
}

return sb.ToString();
}


Technorati tags: , , ,

1 comment:

Anonymous said...

Another alternative:

http://www.filehelpers.com

Cheers
Marcos