Wednesday, June 19, 2019

c# Convert CSV file to DataTable and sort DataTable


using System.IO;
using System.Data;

        static DataTable ConvertCSVToDataTable(string strFilePath)
        {
            DataTable dt = new DataTable();
            try
            {
                using (StreamReader sr = new StreamReader(strFilePath))
                {
                    //Add headers
                    string[] headers = sr.ReadLine().Split(',');
                    foreach (string header in headers)
                    {
                        dt.Columns.Add(header);
                    }
                    //Add Rows
                    while (!sr.EndOfStream)
                    {
                        string[] rows = sr.ReadLine().Split(',');
                        DataRow dr = dt.NewRow();
                        for (int i = 0; i < headers.Length; i++)
                        {
                            //Add each cell to row
                            dr[i] = rows[i];
                        }
                        //Add row to datatable
                        dt.Rows.Add(dr);
                    }
                }

                //Sort the data table
                dt.DefaultView.Sort = "FieldName";
                dt = dt.DefaultView.ToTable();
            }
            catch (Exception e)
            {
                Console.WriteLine("General Exception: {0}", e);
            }

            return dt;
        }

No comments:

Post a Comment