In my last example I had demonstrated the export to
excel in C#, and keeping up my promise now I’ll show you how to export data to
text or csv file. For this example I’ll use same “GetData” method which
we had used in Export to Excel example.
/// <summary>
/// Export to text/csv
/// </summary>
private void
ExportTextFile()
{
var
records = GetData();
var sb = new StringBuilder();
sb.AppendLine("First
Name\tLast Name\tEmail Address\tCity");
foreach (var record in
records)
{
sb.AppendFormat("{0}\t{1}\t{2}\t{3}"
, record.FirstName
, record.LastName
, record.Email
, record.City);
sb.AppendLine();
}
//Get current
response
var
response = HttpContext.Current.Response;
response.BufferOutput = true;
//clear
response
response.Clear();
response.ClearHeaders();
response.ContentEncoding = Encoding.Unicode;
//For csv
export give file name as "Test_Data.csv"
response.AddHeader("content-disposition", "attachment; filename=Test_Data.txt");
response.ContentType = "text/plain";
response.Write(sb.ToString());
response.End();
}
|
And we can check output of our work as:
Tada
ReplyDeleteThis is an excellent component for verifying email addresses:
http://www.kellermansoftware.com/p-37-net-email-validation.aspx
thanks Asava for sharing this.
DeleteIts giving me error "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack."
ReplyDeleteI am using this code in Class file
Hi It's look like you are getting this error, on Response.End, either put this line in try catch block or try to use "HttpContext.Current.ApplicationInstance.CompleteRequest", for more information check this link http://support.microsoft.com/kb/312629/en-us
Deleteor you can see working sample here http://sandeep-tada.blogspot.in/2012/12/export-sample-series-in-c-aspnet.html