Advertisement

Latest Post

Friday, 10 February 2017

Most Significant Way of Exporting DataTable to CSV

How to Export DataTable to CSV using c#

As you know Export data as CSV file in C# is one of the most used functionality in the applications. So here, I am going to sharing how to Export data as CSV using C#.


Following is simple c# code that export data as CSV.

     
      public void ExportToCSV()
        {
            //Fetching user records with GetUserDetails method.
            /// Here you can wirte your own code to fetch recodes as per you DB connections.
            var UserList = repositoryUser.GetUserDetails();
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[5] { new DataColumn("ID", typeof(long)),
            new DataColumn("Name", typeof(string)),
            new DataColumn("Age", typeof(int)),
            new DataColumn("Address", typeof(string)),
            new DataColumn("DOB", typeof(string)),
            });
            foreach (var x in UserList)
            {
                dt.Rows.Add(x.ID, x.Name, x.Age, x.Address, x.DOB);
            }           

            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition","attachment;filename=DataTable.csv");
            Response.Charset = "";
            Response.ContentType = "application/text";

            StringBuilder sb = new StringBuilder();
            for (int k = 0; k < dt.Columns.Count; k++)
            {
                //add separator
                sb.Append(dt.Columns[k].ColumnName + ',');
            }
            //append new line
            sb.Append("\r\n");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int k = 0; k < dt.Columns.Count; k++)
                {
                    //adding separator
                    sb.Append(dt.Rows[i][k].ToString().Replace(",", ";") + ',');
                }
                //adding new line
                sb.Append("\r\n");
            }
            Response.Output.Write(sb.ToString());
            Response.Flush();
            Response.End();          

        }


YOU MAY ALSO LIKE...

Export data as Excel file in C#
Export data as PDF file in C#
Export data as CSV file in C#
Export data as Word file in C#

I hope you are enjoying with this post! Please share with you friends!! Thank you!!!

Government Jobs