C# create csv file and export datatable to csv

This example shows you how to create a csv file in c# and how to export datatable or dataset to csv file in c#. While writing csv file if input data contains double quote(") or comma(,) then csv file will not be generated properly. To overcome this issue we have written a custom method "FormatCSV" in the below example.

Datatable

Output

CS Page Code

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; using System.Data; using System.Diagnostics; using System.Text; using System.Globalization; using System.IO; namespace WebApplication1 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); DataTable dt = GetData(); foreach (DataRow dr in dt.Rows) { foreach (DataColumn dc in dt.Columns) sb.Append(FormatCSV(dr[dc.ColumnName].ToString()) + ","); sb.Remove(sb.Length - 1, 1); sb.AppendLine(); } File.WriteAllText("E:\\Sample\\SampleCSV.csv", sb.ToString()); } DataTable GetData() { DataTable dt = new DataTable(); dt.Columns.Add("StudentID", typeof(int)); dt.Columns.Add("StudentName", typeof(string)); dt.Columns.Add("RollNumber", typeof(int)); dt.Columns.Add("TotalMarks", typeof(int)); dt.Rows.Add(1, "Jame's", 101, 900); dt.Rows.Add(2, "Steave, Smith", 105, 820); dt.Rows.Add(3, "Mark\"Waugh", 109, 850); dt.Rows.Add(4, "Steave,\"Waugh", 110, 950); dt.Rows.Add(5, "Smith", 111, 910); dt.Rows.Add(6, "Williams", 115, 864); return dt; } public static string FormatCSV(string input) { try { if (input == null) return string.Empty; bool containsQuote = false; bool containsComma = false; int len = input.Length; for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++) { char ch = input[i]; if (ch == '"') containsQuote = true; else if (ch == ',') containsComma = true; } if (containsQuote && containsComma) input = input.Replace("\"", "\"\""); if (containsComma) return "\"" + input + "\""; else return input; } catch { throw; } } } }