Tuesday, January 3, 2012

Exporting DataTable To CSV File

Hi All
Once again I feel if you have tried writing to Csv, You must have faced problem of delimiter collision.
Here is the solution:
protected void ExportToCSV(DataTable dataTable, string fileName, NameValueCollection nvcCriteria)
{

HttpContext context = HttpContext.Current;

context.Response.Clear();

//trying to write the criteria in downloaded csv file.
context.Response.Write("Following Criterion is used to generate this Report.");
context.Response.Write(Environment.NewLine);
context.Response.Write("FromDate : " + nvcCriteria["FromDate"]);
context.Response.Write(Environment.NewLine);
context.Response.Write("ToDate : " + nvcCriteria["ToDate"]);
context.Response.Write(Environment.NewLine);
context.Response.Write("QuoteId : " + nvcCriteria["QuoteId"]);
context.Response.Write(Environment.NewLine);
context.Response.Write("QuoteStatus : " + nvcCriteria["StatusText"]);
context.Response.Write(Environment.NewLine);
context.Response.Write("Product : " + nvcCriteria["ProductText"]);
context.Response.Write(Environment.NewLine);
context.Response.Write("AccessType : " + nvcCriteria["AccessText"]);
context.Response.Write(Environment.NewLine);
foreach (DataColumn column in dataTable.Columns)
{

context.Response.Write(column.ColumnName + ",");

}

context.Response.Write(Environment.NewLine);



foreach (DataRow row in dataTable.Rows)
{

for (int i = 0; i < dataTable.Columns.Count; i++)
{

string outputS = EscapeCsvField(row[i].ToString());
//Response.Write(row[i].ToString());
context.Response.Write(outputS + ((i < dataTable.Columns.Count - 1) ? "," : Environment.NewLine));

}

//context.Response.Write(Environment.NewLine);

}

context.Response.ContentType = "text/csv";

context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");

context.Response.End();

}

Below is the EscapeCSVField method for handling delimiter collision.
private string EscapeCsvField(string sFieldValueToEscape)
{

// since we delimit values with a comma, we need to escape commas that are

// actually in the value to escape. We do this by putting a (") quote at

// the front and end of the string.

if (sFieldValueToEscape.Contains(","))
{

// if the string we are escaping already has a (") quote in it, we have to

// 'escape the escape character' by putting double quotes in it's place.

if (sFieldValueToEscape.Contains("\""))
{

return "\"" + sFieldValueToEscape.Replace("\"", "\"\"") + "\"";

}

else
{

// there are no quotes in this string so just escape it by wrapping it in

// quotes.

return "\"" + sFieldValueToEscape + "\"";

}

}

else
{

// There are no commas in this string so just return it as is

return sFieldValueToEscape;

}

}

Happy Programming!

No comments:

Post a Comment