/// <summary> /// Using Data form datatable to export to csv file /// </summary> /// <param name="controller"></param> /// <param name="dt"></param> /// <param name="fileName"></param> public static void ExportToCsvData(Controller controller, DataTable dt, string fileName = "data.csv", string[] columns = null) { string delimiter = ","; controller.Response.Clear(); controller.Response.ContentType = "text/csv;"; controller.Response.ContentEncoding = System.Text.Encoding.UTF8; controller.Response.AppendHeader("Content-type", "application/x-download"); DownloadUtil.AddHeaderContentDisposition(HttpContext.Current.Request, controller.Response, fileName); string value = ""; var builder = new StringBuilder(); //write the csv column headers if (columns == null) { for (int i = 0; i < dt.Columns.Count; i++) { value = dt.Columns[i].ColumnName; // Implement special handling for values that contain comma or quote // Enclose in quotes and double up any double quotes if (value.IndexOfAny(new char[] { '"', ',' }) != -1) { builder.AppendFormat("\"{0}\"", value.Replace("\"", "\"\"")); } else { builder.Append(value); } controller.Response.Write(builder.ToString()); controller.Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine); builder.Clear(); } } else { for (int i = 0; i < columns.Length; i++) { value = columns[i].ToString(); // Implement special handling for values that contain comma or quote // Enclose in quotes and double up any double quotes if (value.IndexOfAny(new char[] { '"', ',' }) != -1) { builder.AppendFormat("\"{0}\"", value.Replace("\"", "\"\"")); } else { builder.Append(value); } controller.Response.Write(builder.ToString()); controller.Response.Write((i < columns.Length - 1) ? delimiter : Environment.NewLine); builder.Clear(); } } //write the data foreach (DataRow row in dt.Rows) { for (int i = 0; i < dt.Columns.Count; i++) { controller.Response.Write(row[i].ToString()); controller.Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine); } } try { controller.Response.End(); } catch (HttpException) { // When canceled. // The remote host closed the connection. The error code is 0x800704CD } }