Home > Net >  Remove some coma separated header values from a csv file and create a datatable from that csv in C#
Remove some coma separated header values from a csv file and create a datatable from that csv in C#

Time:10-27

I have a very big csv file like this (more than 12K rows) ;

    Comment, DateTime   Name,  Age,  Class, Place,  --> these are the header columns
    Good,    03/10/2022, John,  12,    3,     UK,
    Bad,     12/10/2022, Tom,   15,    2,     US

This is a generalized example which shows column names. But it will be more than this columns some times.

I am reading it as shown below

    List<string> lines = File.ReadAllLines(System.IO.Path.ChangeExtension(FileNameWithPath, ".csv")).ToList();

I need a datatable from the above mentioned csv file but i DO NOT want Comment and Place columns in the datatable.

Can anybody show me how we can achieve this ?

Column datatypes :

       DateTime --> typeof(datetime)

       Name     --> typeof(string)

       Age --> typeof(double?)

       Class  --> typeof(int)

CodePudding user response:

You can remove the columns using DataColumnCollection.Remove() after converting from the list to a datatable.

dt.Remove("Comments")

CodePudding user response:

public static DataTable CSVtoDataTable(string filePath)
  {
    DataTable dtData = new DataTable();
    using (StreamReader sReader = new StreamReader(filePath))
    {
        string[] columnHeader = sReader.ReadLine().Split(',');
        foreach (string header in columnHeader)
        {
            dtData.Columns.Add(header);
        }
        while (!sReader.EndOfStream)
        {
            string[] rows = sReader.ReadLine().Split(',');
            DataRow drRow = dtData.NewRow();
            for (int i = 0; i < columnHeader.Length; i  )
            {
                drRow[i] = rows[i];
            }
            dtData.Rows.Add(drRow);
        }

    }

    dtData.Columns.Remove("Comment");
    dtData.Columns.Remove("Place");
        return dtData;
   }
  • Related