How to read a CSV file into a .NET Datatable

后端 未结 22 2452
野性不改
野性不改 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 06:11

    I have been using OleDb provider. However, it has problems if you are reading in rows that have numeric values but you want them treated as text. However, you can get around that issue by creating a schema.ini file. Here is my method I used:

    // using System.Data;
    // using System.Data.OleDb;
    // using System.Globalization;
    // using System.IO;
    
    static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
    {
        string header = isFirstRowHeader ? "Yes" : "No";
    
        string pathOnly = Path.GetDirectoryName(path);
        string fileName = Path.GetFileName(path);
    
        string sql = @"SELECT * FROM [" + fileName + "]";
    
        using(OleDbConnection connection = new OleDbConnection(
                  @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + 
                  ";Extended Properties=\"Text;HDR=" + header + "\""))
        using(OleDbCommand command = new OleDbCommand(sql, connection))
        using(OleDbDataAdapter adapter = new OleDbDataAdapter(command))
        {
            DataTable dataTable = new DataTable();
            dataTable.Locale = CultureInfo.CurrentCulture;
            adapter.Fill(dataTable);
            return dataTable;
        }
    }
    

提交回复
热议问题