在ssis中,当sheetname始终不同时加载excel文件

时间:2013-02-26 17:20:08

标签: ssis

我需要从excel文件(.xlsx)将数据加载到sql server table(2008R2)。我的excel文件名总是不同的,并且工作表名称也总是不同。但是列数和列名总是相同的我有一张excel工作簿。(。xlsx文件)我尝试了Nitesh rai以及Nik-shahriar Nikkhah和其他人提供的解决方案。当我创建包时,所有解决方案都起作用。但是当新文件带有新的工作表名称和新工作表名称时,我的包失败。我很沮丧,真的很沮丧并且很长时间寻找解决方案。没有运气。可以任何身体帮帮我。

2 个答案:

答案 0 :(得分:1)

我确定我迟到了游戏,但您可以使用脚本组件来遍历指定文件夹中包含您期望的部分文件名的excel文件。这将为您提供文件(假设您没有多个具有相似名称的excel文件放在同一文件夹中但出于不同目的)。

为了获取工作表名称,您可以创建OBJECT类型的变量,然后使用以下代码:

Public Sub Main()

    GetExcelSheets()
    'SetExcelConnString(GetExcelConnString)

    Dts.TaskResult = ScriptResults.Success
End Sub

Private Sub GetExcelSheets()
    Dim excelFile, connstr, curTable As String
    Dim excelConnection As OleDb.OleDbConnection
    Dim tablesInFile As DataTable
    Dim tablenameInFile As DataRow
    Dim tableCount As Integer = 0
    Dim tableIndex As Integer = 0
    Dim excelTables As String()
    Dim blnFound As Boolean = False

    ReDim excelTables(0)
    excelFile = Dts.Variables("sFilePath").Value.ToString
    connstr = GetExcelConnString()

    excelConnection = New OleDb.OleDbConnection(connstr)
    excelConnection.Open()

    tablesInFile = excelConnection.GetSchema("Tables")
    tableCount = tablesInFile.Rows.Count

    For Each tablenameInFile In tablesInFile.Rows
        curTable = tablenameInFile.Item("TABLE_NAME").ToString.Trim.ToLower

        If curTable.IndexOf("sheet1$") >= 0 Then   'change this to be part of the sheet name that you are looking for.  It should be unique to the specific sheet
            blnFound = True
            ReDim excelTables(tableIndex)
            excelTables(tableIndex) = "[" + curTable + "]"
            tableIndex += 1
        End If
    Next

    excelConnection.Close()

    Dts.Variables("objExcelSheet").Value = excelTables
End Sub

Private Function GetExcelConnString() As String
    Dim sExtendedProperties, sExtension, sFilePath, sExcelConn As String

    sFilePath = Dts.Variables("sFilePath").Value.ToString
    sExtension = sFilePath.Substring(sFilePath.LastIndexOf("."))
    If sExtension.ToLower = ".xlsx" Then
        sExtendedProperties = ";Extended Properties=""EXCEL 12.0;HDR=NO"";"
    ElseIf sExtension.ToLower = ".xls" Then
        sExtendedProperties = ";Extended Properties=""EXCEL 8.0;HDR=NO;IMEX=1"";"
    Else
        sExtendedProperties = String.Empty
    End If

    sExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sFilePath & sExtendedProperties

    Return sExcelConn
End Function


Private Sub SetExcelConnString(ByVal sExcelConn As String)
    Dts.Connections("Excel").ConnectionString = sExcelConn
End Sub

然后,您可以对该对象使用For Each循环来获取每个工作表名称并处理找到指定工作表时需要执行的操作。

答案 1 :(得分:0)

您唯一的希望是使用外部代码程序集(脚本组件/脚本任务)来处理这种情况。 SSIS抱怨更改的元数据,因为它无法在Excel连接管理器中找到旧的excel文件。您是否尝试过使用SSIS包配置在运行时更改文件名?

这应该能够帮助您随时了解工作簿名称不同的部分。但是,你会遇到更改工作表名称的问题。这是你需要通过脚本组件来解决的问题。