简体   繁体   中英

CSV to DataTable via OleDbDataAdapter - C#

I'm a bit new to C# and have been getting my feet wet. I've been trying to figure out where I'm going wrong here.

What I'm attempting to do: I'd like to import a CSV file into a data table. I can do it easily with a simple "select * from file" query. However when I try to make the query a little more complex I bump into an issue.

I more or less want to sort the DataTable by very specific equation.

Here's the code in question:

        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 name, max_sale_unit_price, max_offer_unit_price, " +
            "( (min_sale_unit_price * 0.85) - max_offer_unit_price ) AS thediff "+
            "FROM [" + fileName + "] " +
            "WHERE (min_sale_unit_price > 0) "+
            "AND ( ((min_sale_unit_price * 0.85) - max_offer_unit_price) > 2000 ) "+
            "ORDER BY thediff DESC";

        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;
        }
    }

I do get an exception on "adapter.Fill(dataTable)" --> OleDB Exception: No value given for one or more required parameters. I have a feeling it's because I'm using the "AS thediff" keyword and attempting to sort by that. What do I need to do to correct this?

   //Sorting the Datatable will return the EnumerableRowCollection<T>

Once datatable is with you you can use this LINQ for order by :

EnumerableRowCollection<DataRow> dr1 = (from row in dt.AsEnumerable()
                                             orderby row["your_column_name"] descending
                                        select row);

        // Dataview's ToTable returns the table 
        // Note : Don't use Dataview.Table method 

        DataTable dv = dr1.AsDataView().ToTable();

or you can use like this :

  DataTable dtSortedTable =  dt.AsEnumerable()
                            .OrderBy(row =>  row.Field<string>("your_column_name"))            
                            .CopyToDataTable();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM