Creating a DataTable from CSV File

前端 未结 5 2077
野趣味
野趣味 2020-12-10 06:59

I\'m working on a project and I need to read a CSV file and then fill a DataSet with its data. I\'ve been searching and I have found some interesting things in OleDB.

相关标签:
5条回答
  • 2020-12-10 07:23

    if nothing special i use this kind of code

    TextReader tr1 = new StreamReader(@"c:\pathtofile\filename",true);
    
    var Data = tr1.ReadToEnd().Split('\n')
    .Where(l=>l.Length>0)  //nonempty strings
    .Skip(1)               // skip header 
    .Select(s=>s.Trim())   // delete whitespace
    .Select(l=>l.Split(',')) // get arrays of values
    .Select(l=>new {Field1=l[0],Field2=l[1],Field3=l[2]});
    
    0 讨论(0)
  • 2020-12-10 07:39

    I always use this CSV library for reading CSV files in through C# its always worked good for me.

    http://www.codeproject.com/KB/database/CsvReader.aspx

    Heres an example of reading a CSF file using the library

    using System.IO;
    using LumenWorks.Framework.IO.Csv;
    
    void ReadCsv()
    {
        // open the file "data.csv" which is a CSV file with headers
        using (CsvReader csv =
               new CsvReader(new StreamReader("data.csv"), true))
        {
            int fieldCount = csv.FieldCount;
            string[] headers = csv.GetFieldHeaders();
    
            while (csv.ReadNextRecord())
            {
                for (int i = 0; i < fieldCount; i++)
                    Console.Write(string.Format("{0} = {1};",
                                  headers[i], csv[i]));
    
                Console.WriteLine();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-10 07:41

    Try including IMEX in the extended properties, which will tell the driver that you have mixed mode data

    Text;HDR=YES;FMT=Delimited;IMEX=1
    
    0 讨论(0)
  • 2020-12-10 07:42

    The best option I have found, and it resolves issues where you may have different versions of Office installed, and also 32/64-bit issues, is FileHelpers.

    It can be added to your project references using NuGet and it provides a one-liner solution:

    CommonEngine.CsvToDataTable(path, "ImportRecord", ',', true);
    
    0 讨论(0)
  • 2020-12-10 07:45

    KBCsv has built-in support for reading into a DataSet:

    using (var reader = new CsvReader(@"C:\data.csv")) {
        reader.ReadHeaderRecord();
        var dataSet = new DataSet();
        reader.Fill(dataSet, "csv-data");
    }
    
    0 讨论(0)
提交回复
热议问题