rofans91
rofans91

Reputation: 3010

Exporting XLS into DataTable - Rows Unsorted

I am exporting an .xls file into datatable. Below are my code:

private DataTable ExportXlsToDt(String path)
{
    OleDbConnection MyConnection = null;
    DataSet DtSet = null;
    OleDbDataAdapter MyCommand = null;
    MyConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + path + "';Extended Properties=Excel 8.0;");

    ArrayList TblName = new ArrayList();

    MyConnection.Open();
    DataTable schemaTable = MyConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
    foreach (DataRow row in schemaTable.Rows)
    {
        TblName.Add(row["TABLE_NAME"]);
    }

    MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + TblName[0].ToString() + "]", MyConnection);
    DtSet = new System.Data.DataSet();

    MyCommand.Fill(DtSet);
    MyCommand.FillSchema(DtSet, SchemaType.Source);

    DataTable dt = new DataTable();
    dt = DtSet.Tables[0];
    MyConnection.Close();
}

However the rows after export is not as sorted as rows before export. Example:

Original

row A

row B

row C

row D

After Export

row D

row C

row A

row B

Can someone advise me on this?

Thank's.

Upvotes: 0

Views: 339

Answers (1)

J. Ed
J. Ed

Reputation: 6752

you have no 'order by' clause on your select; therefore row order isn't guaranteed.
Add an 'order by' clause to MyCommand and you should be good.

Upvotes: 2

Related Questions