服务器上的SSIS包无法导出到Excel

时间:2015-07-03 10:41:40

标签: sql-server excel ssis

我已经创建了一个SSIS包,它可以从我的BIDS中完美运行。但是当从服务器执行时它失败了。

该软件包执行以下操作:

  • 将数据(从SQL数据库中读取)插入Excel文件
  • 通过VB脚本打开Excel文件并删除第2行

我可以看到包可以在Excel文件中正确插入数据。在名为“删除第二行”的步骤中执行VB脚本时失败:

Remove 2ndline: Error: Exception has been thrown by the target of an invocation.

脚本是:

    #Region "Help:  Introduction to the script task"
    'The Script Task allows you to perform virtually any operation that can be accomplished in
    'a .Net application within the context of an Integration Services control flow. 

    'Expand the other regions which have "Help" prefixes for examples of specific ways to use
    'Integration Services features within this script task.
    #End Region
    Option Strict Off

    #Region "Imports"
    Imports System
    Imports System.Data
    Imports System.Math
    Imports Microsoft.SqlServer.Dts.Runtime
    Imports Microsoft.Office.Interop.Excel

    #End Region

    'ScriptMain is the entry point class of the script.  Do not change the name, attributes,
    'or parent of this class.
    <Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute()> _
    <System.CLSCompliantAttribute(False)> _
    Partial Public Class ScriptMain
        Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase

        Private _app As Microsoft.Office.Interop.Excel.Application
        Private _books As Microsoft.Office.Interop.Excel.Workbooks
        Private _book As Microsoft.Office.Interop.Excel.Workbook
        Protected _sheets As Microsoft.Office.Interop.Excel.Sheets
        Protected _sheet1 As Microsoft.Office.Interop.Excel.Worksheet


    #Region "Help:  Using Integration Services variables and parameters in a script"
        'To use a variable in this script, first ensure that the variable has been added to 
        'either the list contained in the ReadOnlyVariables property or the list contained in 
        'the ReadWriteVariables property of this script task, according to whether or not your
        'code needs to write to the variable.  To add the variable, save this script, close this instance of
        'Visual Studio, and update the ReadOnlyVariables and 
        'ReadWriteVariables properties in the Script Transformation Editor window.
        'To use a parameter in this script, follow the same steps. Parameters are always read-only.

        'Example of reading from a variable:
        ' startTime = Dts.Variables("System::StartTime").Value

        'Example of writing to a variable:
        ' Dts.Variables("User::myStringVariable").Value = "new value"

        'Example of reading from a package parameter:
        ' batchId = Dts.Variables("$Package::batchId").Value

        'Example of reading from a project parameter:
        ' batchId = Dts.Variables("$Project::batchId").Value

        'Example of reading from a sensitive project parameter:
        ' batchId = Dts.Variables("$Project::batchId").GetSensitiveValue()
    #End Region

    #Region "Help:  Firing Integration Services events from a script"
        'This script task can fire events for logging purposes.

        'Example of firing an error event:
        ' Dts.Events.FireError(18, "Process Values", "Bad value", "", 0)

        'Example of firing an information event:
        ' Dts.Events.FireInformation(3, "Process Values", "Processing has started", "", 0, fireAgain)

        'Example of firing a warning event:
        ' Dts.Events.FireWarning(14, "Process Values", "No values received for input", "", 0)
    #End Region

    #Region "Help:  Using Integration Services connection managers in a script"
        'Some types of connection managers can be used in this script task.  See the topic 
        '"Working with Connection Managers Programatically" for details.

        'Example of using an ADO.Net connection manager:
        ' Dim rawConnection As Object = Dts.Connections("Sales DB").AcquireConnection(Dts.Transaction)
        ' Dim myADONETConnection As SqlConnection = CType(rawConnection, SqlConnection)
        ' <Use the connection in some code here, then release the connection>
        ' Dts.Connections("Sales DB").ReleaseConnection(rawConnection)

        'Example of using a File connection manager
        ' Dim rawConnection As Object = Dts.Connections("Prices.zip").AcquireConnection(Dts.Transaction)
        ' Dim filePath As String = CType(rawConnection, String)
        ' <Use the connection in some code here, then release the connection>
        ' Dts.Connections("Prices.zip").ReleaseConnection(rawConnection)
    #End Region

        'This method is called when this script task executes in the control flow.
        'Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
        'To open Help, press F1.

        Public Sub Main()

            Try
                Dim FileName As String = ""
                If Dts.Variables.Contains("DestinationPath") = True Then
                    FileName = CType(Dts.Variables("DestinationPath").Value, String)
                End If

                OpenExcelWorkbook(FileName)

                _sheet1 = CType(_sheets(1), Microsoft.Office.Interop.Excel.Worksheet)
                _sheet1.Activate()

                Dim range As Microsoft.Office.Interop.Excel.Range = _sheet1.Rows(2)
                range.Delete(Microsoft.Office.Interop.Excel.XlDeleteShiftDirection.xlShiftUp)
                DoRelease(range)
                DoRelease(_sheet1)
                CloseExcelWorkbook()
                DoRelease(_book)
                _app.Quit()
                DoRelease(_app)
                Dts.TaskResult = ScriptResults.Success
            Catch ex As Exception

                MsgBox(ex.ToString())
            End Try


        End Sub
        Protected Sub OpenExcelWorkbook(ByVal fileName As String)
            'try
            '{
            _app = New Microsoft.Office.Interop.Excel.Application()
            If _book Is Nothing Then
                _books = _app.Workbooks
                _book = _books.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
                _sheets = _book.Worksheets
            End If
            '}
            'catch(Exception ex)
            '{
            ' Console.WriteLine(ex.ToString());
            '}

        End Sub
        Protected Sub CloseExcelWorkbook()
            _book.Save()
            _book.Close(False, Type.Missing, Type.Missing)
        End Sub
        Protected Sub DoRelease(ByVal o As Object)
            Try
                If Not o Is Nothing Then
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(o)
                End If
            Finally
                o = Nothing
            End Try
        End Sub

    #Region "ScriptResults declaration"
        'This enum provides a convenient shorthand within the scope of this class for setting the
        'result of the script.

        'This code was generated automatically.
        Enum ScriptResults
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        End Enum

    #End Region

    End Class

变量“DestinationPath”到达Excel文件。此路径在脚本外部工作(即,它可以在前一步骤中填充文件中的数据)。它在脚本中的BIDS中也有效。我还确保将其作为ReadOnlyVariable提供给脚本。所以我非常有信心这个变量不是问题。

我的服务器是Windows 2012 R2(64位)

正在SQL Server 2012 - 11.0上执行该程序包。

我已在服务器上安装了Excel 2013.

我创建了以下文件夹,因为这也可能导致问题(我已阅读):C:\ Windows \ SysWOW64 \ config \ systemprofile \ Desktop

我的脚本的调用者是我的管理员用户标识 - 此用户标识能够在服务器上使用Excel。

1 个答案:

答案 0 :(得分:2)

是否有任何理由我们无法使用常规Excel连接管理器插入数据,而不是删除第2行,只是从不发送它?使用条件性拆分将其虹吸掉。这是一个simple example。以下是使用SSIS默认Excel连接管理器的advanced example。我还想在脚本任务中使用Interop.Excel给予智慧之珠。它当然可以导致这些类型的“但是,它适用于我的机器”场景。阅读KB257757,看看为什么微软不鼓励这类事情。但是,Interop.Excel只能做一些事情,比如保存为PDF或运行宏。你没有做过这些事情,为什么不试试常规的Excel连接器呢?