Home > SQL, c# > Reading csv file in datatable

Reading csv file in datatable

Recently I had to work on one problem where I had to read the csv file and filling up the data table with the csv file data. I used the OLEDBAdapter to accomplish that with just few lines of code. Following is the code :

            string query = "SELECT Symbol, [Name of Company], FROM [just file name with extension]";
            string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + [csv file path without file name] + ";" + "Extended Properties=’text;HDR=YES;’";

            //create dataadapter object
            OleDbDataAdapter adapter = new OleDbDataAdapter(query, connStr);

            // create table
            DataTable dtSymbolDetails = new DataTable("ScriptDetails");
            dtSymbolDetails.Columns.Add("Symbol");
            dtSymbolDetails.Columns.Add("Name of Company");

            // fill the table with data using adapter
            adapter.Fill(dtDetails);

So above code fills up the details of the csv file in the data table for further use.

Also note the text in red above. If column name contains the space then in query the column name should be put between [ ]. I learned it in bit hard way. It shows I’m so poor in my sql knowledge.

Categories: SQL, c# Tags: , ,
  1. Bipin Singh
    August 13, 2009 at 4:16 pm | #1

    Dear Concerned,

    this code does’n work at my side. i’ll be very thankful if you can send me the proper code to read the data from .csv file & update into sql server databse.

    thanks & regards,
    Bipin Singh

    • August 14, 2009 at 9:48 am | #2

      Let me know what is the problem you are facing at your end then can suggest something.

  2. Acma
    October 27, 2009 at 7:07 pm | #3

    Hello everyone,
    I am facing a problem like this.
    I am trying to develop a tool for import CSV files into existing tables in my DB.
    but i’m still facing the problem of reading csv into datatable to copy or insert it into my DB table.
    Any help?

  1. No trackbacks yet.