在SSIS脚本任务中激活特定的Excel工作表

时间:2017-02-27 18:50:13

标签: sql-server excel csv ssis script-task

我有一个脚本任务,它打开一个excel文件并将其保存为.csv,但它保存了随文件打开的工作表,而我想选择保存为.csv的工作表,这是脚本我'我目前正在使用:

    Public Sub Main()

    Dim oMissing As Object = System.Reflection.Missing.Value
    Dim xl As New Microsoft.Office.Interop.Excel.ApplicationClass()
    Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
    Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet
    Dim laPath As String = "C:\Filename.xlsx"
    xlBook = DirectCast(xl.Workbooks.Open(laPath, oMissing, oMissing, oMissing, oMissing, oMissing,
    oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
    oMissing, oMissing, oMissing), Workbook)

    xl.DisplayAlerts = False
    xlSheet = DirectCast(xlBook.Worksheets.Item(1), Worksheet)
    xlBook.SaveAs("C:\Filename.csv", 6, oMissing, oMissing, oMissing, oMissing,, oMissing, oMissing, oMissing, oMissing, oMissing)
    xl.Application.Workbooks.Close()
    Dts.TaskResult = ScriptResults.Success
End Sub

我想我必须使用xlbook.Worksheets("Sheet1").Activate,但我似乎无法找到它。

1 个答案:

答案 0 :(得分:1)

您必须按名称打开工作表并使用Select()函数选择它:

xlSheet = xlBook.Worksheets("Sheet1")
xlSheet.Select()

您的代码如下:

Public Sub Main()

    Dim oMissing As Object = System.Reflection.Missing.Value
    Dim xl As New Microsoft.Office.Interop.Excel.ApplicationClass()
    Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
    Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet
    Dim laPath As String = "C:\Filename.xlsx"
    xlBook = xl.Workbooks.Open(laPath)
    xl.DisplayAlerts = False
    xlSheet = xlBook.Worksheets("Sheet1")
    xlSheet.Select()
    xlBook.SaveAs("C:\Filename.csv", Excel.XlFileFormat.xlCSV,Excel.XlSaveAsAccessMode.xlNoChange)
    xl.Application.Workbooks.Close()
    Dts.TaskResult = ScriptResults.Success
End Sub