Saturday, 26 August 2017

How to convert datatable into csv/excel file in C#

How to convert datatable into csv/excel file in C#


Often we require to convert the datatable in context in a c# code into a plain text csv (comma separated values) or a excel readable file. Here i have created a c#  console application code snipped to convert a sample datatable into csv notepad file or csv excel readable file. You can utilize it where you need it.
Hope it would be helpful:

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Text;
using System.Data;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        public  static void Main(string[] args)
        {

            //Create a sample datatable
            DataTable dt=new DataTable();
            dt.Columns.Add("FisrtName", typeof(string));
            dt.Columns.Add("LastName", typeof(string));

            DataRow dr1 = dt.NewRow();
            dr1["FisrtName"]="Vishal";
            dr1["LastName"]="Grade";
            dt.Rows.Add(dr1);

            DataRow dr2 = dt.NewRow();
            dr2["FisrtName"] = "Tony";
            dr2["LastName"] = "Stark";
            dt.Rows.Add(dr2);

            String result = DataTableToCSV(dt, ',');

            //Wrire the result comma seprated string to a csv file which can be opened in excel
            System.IO.File.WriteAllText(@"D:\\result.csv", result);

            //Wrire the result comma seprated string to a csv text file 
            System.IO.File.WriteAllText(@"D:\\result.txt", result);
            

            Console.Write(result);
            
        }
        //Function to convert datatble content into comma separated string
        public static string DataTableToCSV(DataTable datatable, char seperator)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < datatable.Columns.Count; i++)
            {
                sb.Append(datatable.Columns[i]);
                if (i < datatable.Columns.Count - 1)
                    sb.Append(seperator);
            }
            sb.AppendLine();
            foreach (DataRow dr in datatable.Rows)
            {
                for (int i = 0; i < datatable.Columns.Count; i++)
                {
                    sb.Append(dr[i].ToString());

                    if (i < datatable.Columns.Count - 1)
                        sb.Append(seperator);
                }
                sb.AppendLine();
            }
            return sb.ToString();
        }
    }
}





//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Happy learning...!!

No comments:

Post a Comment