I had to go dig this up since it was not in the first click in search engine.
It is much better to go to the schema tables of the OleDb since it defines the schema the provider gave for the OleDb connection. Most are querying the Table and getting the schema information from there, and if the table is very large the query could take more time. Time might be irrelevant since we are talking about excel tables and most excel table sizes are small.
The Original poster was mostly there, they just needed a select statement on their schema columns table to select the schema data for their table:
DataRow[] shtRows = schemaDT.Select("[TABLE_NAME] = 'Sheet1$'");
This solution is provider independent and there is no need to guess or know how the schema of your dataset is created.
The OleDb contains tables that outline the schema definition of the importing data. Since the provider does a bunch of items behind the scenes (i.e. Auto forces data type to number even if you specify force to text [IMEX=1] due to it taking a sample of first few entries).
The schema tables can be retrieved by the GetOleDbSchemaTable() function. Below the [XXX] can be replace with any item from the OleDbSchemaGuid class. To answer the question here Columns was used:
DataTable schemaDT = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.[XXX], null);
Columns -- Returns the columns of tables (including views) defined in the catalog that is accessible to a given user.
This can pull out the column names:
using System;
using System.Linq;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string excelFilePath = @"C:\myexcelfile.xlsx";
string providerString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml; HDR=YES;IMEX=1\";";
List<string> columnNames = new List<string>();
using (OleDbConnection oleConn = new OleDbConnection(String.Format(providerString, excelFilePath)))
{
oleConn.Open();
DataTable schemaDT = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, null);
DataRow[] shtRows = schemaDT.Select("[TABLE_NAME] = 'Sheet1$'");
columnNames = shtRows.Select(o => o.Field<string>("COLUMN_NAME")).ToList();
}
Console.WriteLine(String.Join("\n", columnNames));
Console.ReadLine();
}
}
}