Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading a CSV into a Datatable without knowing the structure

I am trying to read a CSV into a datatable.

The CSV maybe have hundreds of columns and only up to 20 rows.

It will look something like this:

+----------+-----------------+-------------+---------+---+
|  email1  |     email2      |   email3    | email4  | … |
+----------+-----------------+-------------+---------+---+
| ccemail1 | anotherccemail1 | 3rdccemail1 | ccemail |   |
| ccemail2 | anotherccemail2 | 3rdccemail2 |         |   |
| ccemail3 | anotherccemail3 |             |         |   |
| ccemail4 | anotherccemail4 |             |         |   |
| ccemail5 |                 |             |         |   |
| ccemail6 |                 |             |         |   |
| ccemail7 |                 |             |         |   |
| …        |                 |             |         |   |
+----------+-----------------+-------------+---------+---+

i am trying to use genericparser for this; however, i believe that it requires you to know the column names.

string strID, strName, strStatus;
using (GenericParser parser = new GenericParser())
{
    parser.SetDataSource("MyData.txt");

    parser.ColumnDelimiter = "\t".ToCharArray();
    parser.FirstRowHasHeader = true;
    parser.SkipStartingDataRows = 10;
    parser.MaxBufferSize = 4096;
    parser.MaxRows = 500;
    parser.TextQualifier = '\"';

    while (parser.Read())
    {
      strID = parser["ID"];  //as you can see this requires you to know the column names
      strName = parser["Name"];
      strStatus = parser["Status"];

      // Your code here ...
    }
}

is there a way to read this file into a datatable without know the column names?

like image 221
Alex Gordon Avatar asked Dec 15 '22 21:12

Alex Gordon


1 Answers

It's so simple!

        var adapter = new GenericParsing.GenericParserAdapter(filepath);
        DataTable dt = adapter.GetDataTable();

This will automatically do everything for you.

like image 150
Alex Gordon Avatar answered Mar 06 '23 22:03

Alex Gordon