2013-08-07 36 views
2

我基本上設置一個程序,從Excel導入到T-SQL SQL:如何使用動態工作表名稱導入Excel文件? (T-SQL)

SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;HDR=YES;Database=C:\report.xls','select * from [name555$]') 

的name555由一個固定的名稱,而555從什麼似乎是隨機的三位數數。當報告找到我時,有時名稱是555,有時候是439,390等。

有沒有一種方法可以指示SQL服務器(最好在T-SQL中,因爲這正是我現在使用的)來讀取動態的名字?它是XLS文件中的唯一表格,但它是

例如在VBA中,您可以使用工作表作爲name1 $ name或作爲「sheet1 $」索引。那麼,我希望有人可以幫忙:)

回答

1

您可以查詢工作簿的SCHEMA來檢索TABLE(工作表)名稱。如果您的工作簿中只有一個工作表,則第一個有效的TABLE_NAME將成爲工作表的名稱。

下面給出(在VB.NET代碼中)是一種幫助器方法,我一直使用這種任務。該函數的返回值爲您放置名稱的括號,以便它可以在SQL語句中使用。

''' <summary> 
''' Returns the name of the first worksheet in an Excel workbook. 
''' </summary> 
''' <param name="connectString">OleDb connection string for an Excel workbook.</param> 
''' <returns></returns> 
''' <remarks></remarks> 
Public Shared Function GetTableName(ByVal connectString As String) As String 

    Dim dtSheets As New DataTable 
    Dim tmp As String = "" 

    Using cn As New OleDbConnection(connectString) 
    cn.Open() 
    dtSheets = cn.GetSchema("Tables") 
    End Using 

    For Each rw As DataRow In dtSheets.Rows 
    'Get the name of the first worksheet in the file that ends 
    'with a $. 
    tmp = rw("TABLE_NAME") 
    'Check to see if the table name is surrounded by apostorphes. 
    If tmp.StartsWith("'") And tmp.EndsWith("'") Then 
     'Remove the apostrophes. 
     tmp = tmp.TrimEnd("'") 
     tmp = tmp.TrimStart("'") 
    End If 

    If tmp.EndsWith("$") Then 
     Exit For 
    Else 
     tmp = "" 
    End If 
    Next 

    Return "[" & tmp & "]" 

End Function 
相關問題