Home » excel » c# – Can I get the Excel row number using OleDB?

c# – Can I get the Excel row number using OleDB?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am processing Excel data in C# (and SQL Server). I need to be able to report back to end user on any excel rows that where problematic. The natural way to do that is to give the Excel row number. However it isn’t clear how I can get that row number for reference.

I have something like this:

OleDbCommand cmd = new OleDbCommand("SELECT * FROM MyWorkSheet$", conn);

and want something like this:

OleDbCommand cmd = new OleDbCommand("SELECT ExcelRowId,* FROM MyWorkSheet$," conn);

SQL’s: ROW_NUMBER() does work because I can’t provide an appropriate ORDER BY.
Excel’s: ROW() is not accessible in the query string.

How to&Answers:

So far the answer seems to be “No,” but I can create it later.

int row;
foreach (DataTable t in ds.Tables)
{
    t.Columns.Add("RowNum",typeof(Int32));
    row = 1;
    foreach (DataRow r in t.Rows)
    {
        r["RowNum"] = row++;
    }
}

This appears to be reliable, but it still feels like the sort of thing that can just happen more naturally.

Answer:

Having the following sample code as a basis (Karl Kieninger):

int row;
foreach (DataTable t in ds.Tables)
{
    t.Columns.Add("RowNum",typeof(Int32));
    row = 1;
    foreach (DataRow r in t.Rows)
    {
        r["RowNum"] = row++;
    }
}

The Excel row number can be obtained this way:

Each Datatable object (

DataTable t;

) has a DataTable.Rows Property (

t.Rows

) that returns a DataRowCollection Class. Using the DataRowCollection.IndexOf(DataRow) Method (

t.Rows.IndexOf(r)

), you can know the index of the row in the Datatable which relates with the row number in the Excel file. So, replacing row++ by r.IndexOf(r) can do the job:

int row;
foreach (DataTable t in ds.Tables)
{
    t.Columns.Add("RowNum",typeof(Int32));
    row = 1;
    foreach (DataRow r in t.Rows)
    {
        r["RowNum"] = r.IndexOf(r);
    }
}