在不知道结构的情况下将 CSV 读入数据表

l--*_*''' 4 .net c# csv datatable

我正在尝试将 CSV 读入数据表。

CSV 可能有数百列,但最多只有 20 行。

它看起来像这样:

+----------+-----------------+-------------+---------+---+
|  email1  |     email2      |   email3    | email4  | … |
+----------+-----------------+-------------+---------+---+
| ccemail1 | anotherccemail1 | 3rdccemail1 | ccemail |   |
| ccemail2 | anotherccemail2 | 3rdccemail2 |         |   |
| ccemail3 | anotherccemail3 |             |         |   |
| ccemail4 | anotherccemail4 |             |         |   |
| ccemail5 |                 |             |         |   |
| ccemail6 |                 |             |         |   |
| ccemail7 |                 |             |         |   |
| …        |                 |             |         |   |
+----------+-----------------+-------------+---------+---+
Run Code Online (Sandbox Code Playgroud)

我正在尝试为此使用genericparser;但是,我相信它需要您知道列名。

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 ...
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在不知道列名的情况下将此文件读入数据表?

l--*_*''' 7

太简单了!

        var adapter = new GenericParsing.GenericParserAdapter(filepath);
        DataTable dt = adapter.GetDataTable();
Run Code Online (Sandbox Code Playgroud)

这将自动为您做所有事情。