C# Simple CSV Excel export

protected void btnDownload_Click(object sender, EventArgs e){    StringBuilder strResponse = new StringBuilder();    //Heading    strResponse.AppendLine(string.Format("{0},{1}", "EndDate", "KWH Usage"));    //For Each Data Point    strResponse.AppendLine(string.Format("{0},{1}", "2011-10-10", "11.11"));    strResponse.AppendLine(string.Format("{0},{1}", "2011-10-11", "11.11"));    HttpResponse Export = HttpContext.Current.Response;    Export.Clear();    Export.ContentType = "application/octet-stream";    Export.AddHeader("Content-Length", strResponse.Length.ToString());    Export.AddHeader("Content-Disposition", "attachment; filename=CSVFile.csv");    System.Text.Encoding enc = System.Text.Encoding.UTF8;    byte[] fileBytes = enc.GetBytes(strResponse.ToString());    Export.OutputStream.Write(fileBytes, 0, fileBytes.Length);    Export.Flush();    Export.Close();}

See simple class on Stack Overflow

Leave a Reply

Your email address will not be published. Required fields are marked *