tags:

views:

133

answers:

2

I am trying to load an Excel 97 single tabbed spreadsheet into a SQL server table using the OleDbDataAdapter function. From all the documentation I have found, the first parameter should be "select * from [sheet1$]". This works fine for me only if the tab in the worksheet is named Sheet1. If I change what's in the [] brackets to the actual tab name, it also works fine.

The issue is that the spreadsheet being loaded is coming from another system and that system changes the tab name with each load. How can a figure out what the tab name is so that my users don't have to open the spreadsheet and rename the tab?

A: 

I've looked into this in the past, and I've always come to the conclusion that I had to enforce tab names on the people giving me the spreadsheets, there doesn't seem to be a reliable way to find them.

Aric TenEyck
+1  A: 

Ok, first, open an OleDB connection to your Excel spreadsheet.

Then, use something like the following (shown in VB.NET):

Imports System.Data
Imports System.Data.Odbc
Imports System.Data.OleDb

Dim DSN As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MYEXCELFILE.XLS;Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;MAXSCANROWS=12"""
Dim OleDbConn As New OleDbConnection(DSN)
OleDbConn.Open()
Dim tables As System.Data.DataTable = OleDbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim tableName As String
Dim canBeImported As Boolean
For Each dr As System.Data.DataRow In tables.rows
    tableName = dr.Item("TABLE_NAME").ToString
    canBeImported = (tableName.IndexOfAny(New Char() {" ","[","]","'","""","`",";"}) < 0)
Next
OleDbConn.Close()

This will loop through all of the tables in the Excel file (table = sheets or named ranges) and get the name of each. In addition, it will filter out any tables that have characters in them that can't be accessed via ODBC (spaces are the most common issue).

richardtallent
What name spaces do I need to import to get this to compile?
These should cover you:System.DataSystem.Data.OdbcSystem.Data.OleDb
richardtallent
And where do I add the actual spreadsheet file name for this to work as well?
I sort of assumed you already had an OleDB connection open that could be reused.
richardtallent
Added the opening of the OleDb connection, with DSN
richardtallent
This worked except I needed to open the connection before the tables DIM:Dim OleDbConn As New OleDbConnection(DSN)OleDbConn.Open()Dim tables As System.Data.DataTable = OleDbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Thanks, fixed to add Open() and Close() calls. I'm Pretty sure the Close() can be done directly after GetOleDbSchemaTable() but left it open assuming you would be doing other work inside the loop to query those tables.
richardtallent