0

ExcelDataReader with .NetCore 1.1 does not support GetOrdinal. Calling the GetOrdinal method results in an exception:

'Method is not supported'

while (reader.Read())
{
    var id = reader.GetOrdinal("id");
    ...
}    

I believe the intent is use the ExcelDataReader.DataSet package instead, however that is not compatible with .NetCore.

Is there any known work around of getting the columns by name rather than by Index?

As the following works but is reliant on the columns being in a certain order:

while (reader.Read())
{
    var id = reader.GetValue(0);
    ...
}
shA.t
  • 16,580
  • 5
  • 54
  • 111
Mohand Mokri
  • 75
  • 1
  • 8

1 Answers1

0

Unfortunately for now there is no way to use it from ExcelDataReader, because even in source code we just get:

    public string GetName(int i) => throw new NotSupportedException();
    public int GetOrdinal(string name) => throw new NotSupportedException();

And as you said DataSet not supported by .NET Core 1 yet, but if believe this link it should be in .NET Core 2. Maybe then version of ExcelDataReader.DataSet for .NET Core will appear. For now you should write your own implementation of GetOrdinal, which also mentioned in this discussion. You can write your easy implementation (which not handle the case with 2 or more columns with the same name and works if your column names on the 1st row of your sheet) like this for now:

    public static class ExcelExtensionMethods
    {
        static Dictionary<int, string> _columns = new Dictionary<int, string>();

        public static int GetOrdinalCustom(this IExcelDataReader reader, string colName)
        {
            if (reader.Depth == 0 && _columns.Count<reader.FieldCount)
                FillColumns(reader);

            var columnIndex = _columns.Any(xx => xx.Value.Contains(colName.ToLower()))
                ? _columns.FirstOrDefault(xx => xx.Value.Contains(colName.ToLower())).Key
                : -1;

            return columnIndex;
        }

        private static void FillColumns(IExcelDataReader reader)
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                _columns.Add(i, reader.GetValue(i).ToString().ToLower());
            }
        }
    }

And use in your code like below:

    var author = reader.GetOrdinalCustom("Author");
    var mark = reader.GetOrdinalCustom("Mark");
user2771704
  • 5,994
  • 6
  • 37
  • 38