How to read a CSV file into a .NET Datatable

后端 未结 22 2449
野性不改
野性不改 2020-11-22 05:12

How can I load a CSV file into a System.Data.DataTable, creating the datatable based on the CSV file?

Does the regular ADO.net functionality allow this?

22条回答
  •  不要未来只要你来
    2020-11-22 05:52

    I have decided to use Sebastien Lorion's Csv Reader.

    Jay Riggs suggestion is a great solution also, but I just didn't need all of the features that that Andrew Rissing's Generic Parser provides.

    UPDATE 10/25/2010

    After using Sebastien Lorion's Csv Reader in my project for nearly a year and a half, I have found that it throws exceptions when parsing some csv files that I believe to be well formed.

    So, I did switch to Andrew Rissing's Generic Parser and it seems to be doing much better.

    UPDATE 9/22/2014

    These days, I mostly use this extension method to read delimited text:

    https://github.com/Core-Techs/Common/blob/master/CoreTechs.Common/Text/DelimitedTextExtensions.cs#L22

    https://www.nuget.org/packages/CoreTechs.Common/

    UPDATE 2/20/2015

    Example:

    var csv = @"Name, Age
    Ronnie, 30
    Mark, 40
    Ace, 50";
    
    TextReader reader = new StringReader(csv);
    var table = new DataTable();
    using(var it = reader.ReadCsvWithHeader().GetEnumerator())
    {
    
        if (!it.MoveNext()) return;
    
        foreach (var k in it.Current.Keys)
            table.Columns.Add(k);
    
        do
        {
            var row = table.NewRow();
            foreach (var k in it.Current.Keys)
                row[k] = it.Current[k];
        
            table.Rows.Add(row);
        
        } while (it.MoveNext());
    }
    

提交回复
热议问题