从SQL任务导出到Excel

时间:2015-10-28 14:40:43

标签: excel ssis business-intelligence

我需要从Sybase数据库中提取信息并将其放入Excel文件中。由于这个提取使用子查询,我使用SQL任务来提取信息并将其放入变量(Data type = Object)。所以,我需要从变量中获取数据并将其保存到Excel文件中。这就是我到现在所拥有的:

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

这是解决方案: enter image description here enter image description here

然后编辑脚本并将以下代码添加到main函数:


Public Sub Main()
        '
        ' Add your code here
        '

        Dim varExcelApplication As Object
        Dim varExcelBook As Object
        Dim varExcelSheet As Object
        Dim varNumeroFila As Integer
        Dim varNumeroColumna As Integer
        Dim varResults As DataSet
        Dim varRow As DataRow
        Dim varColumn As DataColumn

        Try
            ' Crea la instancia de Excel
            varExcelApplication = CreateObject("Excel.Application")
            varExcelBook = varExcelApplication.Workbooks.Add()
            varExcelSheet = varExcelBook.ActiveSheet
            varExcelApplication.Visible = False
            varExcelApplication.DisplayAlerts = False

            ' Carga los resultados del query
            varResults = CType(Dts.Variables("varRecordSetEstimaciones").Value, DataSet)

            For Each varTabla As DataTable In varResults.Tables
                varNumeroFila = 1
                For Each varRow In varTabla.Rows
                    varNumeroColumna = 1
                    For Each varColumn In varTabla.Columns
                        ' Añade la cabecera para la primera fila
                        If varNumeroFila = 1 Then
                            varExcelSheet.Cells(1, varNumeroColumna) = varColumn.ColumnName.ToString
                        End If
                        varExcelSheet.Cells(varNumeroFila + 1, varNumeroColumna) = varRow(varColumn.Ordinal).ToString
                        varNumeroColumna = varNumeroColumna + 1
                    Next
                    varNumeroFila = varNumeroFila + 1
                Next
            Next

            ' Guarda el archivo
            varExcelBook.SaveAs(Dts.Variables("varPath").Value.ToString & "\Estimaciones.xlsx")
            varExcelApplication.Workbooks.Close()
            varExcelApplication.Quit()

            Dts.TaskResult = ScriptResults.Success
        Catch ex As Exception
            MsgBox(ex.Message)
            Dts.TaskResult = ScriptResults.Failure
        End Try

    End Sub