Search This Blog

Saturday, May 21, 2011

Export Data into CSV file using Asp.net

How to use below code.

First create one default.aspx page and add below code into code behind file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string[] mylist = new string[5]; //Declaring the string array;

//Assigning values to each element in the array
mylist[0] = "Hello";
mylist[1] = "how";
mylist[2] = "are";
mylist[3] = "you";
mylist[4] = "?";

//Creating a new List of type
List StringtoList = new List(mylist.Length);

//AddRange is a method of List objects that enables the conversion.
//We just need to pass the reference to the array.
StringtoList.AddRange(mylist);

CSVExporter.WriteToCSV(StringtoList);
}
}


Then create one CSVExporter.cs file into app_code and add below code into class file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;

///

/// Summary description for CSVExporter
///
public class CSVExporter
{
public static void WriteToCSV(List personList)
{
string attachment = "attachment; filename=PersonList.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
WriteColumnName();
foreach (String person in personList)
{
WriteUserInfo(person);
}
HttpContext.Current.Response.End();
}

private static void WriteUserInfo(String person)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(person);
//AddComma(person.Name, stringBuilder);
//AddComma(person.Family, stringBuilder);
//AddComma(person.Age.ToString(), stringBuilder);
//AddComma(string.Format("{0:C2}", person.Salary), stringBuilder);
HttpContext.Current.Response.Write(stringBuilder.ToString());
HttpContext.Current.Response.Write(Environment.NewLine);
}

private static void AddComma(string value, StringBuilder stringBuilder)
{
stringBuilder.Append(value.Replace(',', ' '));
stringBuilder.Append(", ");
}

private static void WriteColumnName()
{
string columnNames = "Name, Family, Age, Salary";
HttpContext.Current.Response.Write(columnNames);
HttpContext.Current.Response.Write(Environment.NewLine);
}
}

Then press f5 and you will get result.

No comments: