In this tutorial, I will show you how to write sample data into a csv format and force the data to be downloaded as stream. I will use a StringBuilder object to append the content. For the example data, I will populate a simple customers data information that will contain customer id, name, email.
Firstly let's build the sample customer data. We will create a CustomerInfo object and a function that will return a list of CustomerInfo object list.
//Customer Info object that will hold customer information. public class CustomerInfo { public int CustomerID { get; set; } public string Name { get; set; } public string Email { get; set; } }
Now it is time to create a simple code routine that will write the data into csv text format and will force it as a downloaded stream.
public partial class DownloadCSV : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnDownload_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); sb.Append(string.Format("{0},{1},{2}", "CustomerID", "Name", "Email") + Environment.NewLine); List<CustomerInfo> customerList = GetCustomers(); foreach (CustomerInfo objCustomer in customerList) { sb.Append(string.Format("{0},{1},{2}", objCustomer.CustomerID.ToString(), objCustomer.Name, objCustomer.Email) + Environment.NewLine); } byte[] bytes = Encoding.ASCII.GetBytes(sb.ToString()); if (bytes != null) { Response.Clear(); Response.ContentType = "text/csv"; Response.AddHeader("Content-Length", bytes.Length.ToString()); Response.AddHeader("Content-disposition", "attachment; filename=\"sample.csv" + "\""); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); } } //function that will return a list of customer information. public List<CustomerInfo> GetCustomers() { List<CustomerInfo> customerList = new List<CustomerInfo>(); customerList.Add(new CustomerInfo { CustomerID = 1, Name = "Name 1", Email = "sample1@bytutorial.com" }); customerList.Add(new CustomerInfo { CustomerID = 2, Name = "Name 2", Email = "sample2@bytutorial.com" }); customerList.Add(new CustomerInfo { CustomerID = 3, Name = "Name 3", Email = "sample3@bytutorial.com" }); return customerList; } }
One thing to remember, as CSV separate the field or each partial data with comma, if the partial data contains a comma, for ex: some data like address information like 32 george st, NSW Sydney. So you will need to wrap the content with double quote like "32 george st, NSW Sydney".