在不知道结构的情况下将CSV读取到数据表中 [英] reading a CSV into a Datatable without knowing the structure

查看:97
本文介绍了在不知道结构的情况下将CSV读取到数据表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将CS​​V读取到数据表中.

I am trying to read a CSV into a datatable.

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

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

它看起来像这样:

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

我正在尝试使用 genericparser 为此;但是,我认为这需要您知道列名.

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?

推荐答案

非常简单!

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

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

This will automatically do everything for you.

这篇关于在不知道结构的情况下将CSV读取到数据表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆