tags:

views:

1008

answers:

3

I have users that name their sheets all sorts of crazy things, but I want to be able to get the first sheet of the Excel document regardless of what it is named.

I currently use:

OleDbDataAdapter adapter = new OleDbDataAdapter(
"SELECT * FROM [sheetName$]", connString);

How would I go about getting the first sheet no matter what it is named?

Thank you.

+1  A: 

You can use the GetOleDbSchemaTable (VB) or GetOleDbSchemaTable (C#).

Using the Tables Enum it will return a list of all the worksheet names, which you can then use to dynamically build the required SQL.

You can use:

MySchemaTable = MyConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})

All the Worksheets names will be returned as part of a DataTable you can them itterate through.

Using the OleDbSchemaGuid information can be retrieved on

  • Columns
  • Foreign keys
  • Indexes
  • Primary keys
  • Tables
  • Views

Full MSDN documentation available here

Diago
it looks like that returns a datatable, how do I get the sheet name out? is it a named field?
naspinski
also, what parameters do I pass in for the restrictions : Object [ ]?
naspinski
@naspinski - The articles I linked contains all the required information. I haven't worked with OLEDB in the last 2 years. If I recall correctly the table name will be in the COLUMN_NAME field.
Diago
A: 

ended up using this:

using (OleDbConnection conn = new OleDbConnection(connString))
{
    conn.Open();
    dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
    Sheet1= dtSchema.Rows[0].Field<string>("TABLE_NAME");
}
naspinski