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();
}
1 comment:
Another alternative:
http://www.filehelpers.com
Cheers
Marcos
Post a Comment