Script Task - convert excel to txt
Hi,
I have an .xls file in a shared folder. How can we convert this file into a txt file and save it with a different name in the same or different folder.
Thanks
Syed Faiz
I’m not sure why you want to do that and your requirements but you can do this with a simple File System task instead of Script task.
Create a variable (strDest) of String type and provide the value - C:\SSISPackages\First\Forums\ExcelToTxt.txt
C:\SSISPackages\First\Forums\ is your destination path and ExcelToTxt is your Excel file name.
Drop a File System task
Select the Operation – Copy file
Source connection – Provide the connection to your Excel file
Destination connection – Provide the connection to your Destination folder (like - C:\SSISPackages\First\Forums\ i.e. where you want to copy the Excel file as Text file)
Now, go to your Destination Connection properties > Expressions > Connection String
> Select the variable – strDest as Expression
Execute the package.
Narsimha
Similar Messages
-
Problem with Script Task formatting excel
Hi Experts,
I am creating a package and using Script task to format one excel dimension file, now the problem is if I execute the package from BIDS designer with static values then the package executes fine with excel file formatted perfectly fine but if I execute same package in BPC via Data manager with values used from variables it gives error on script task message:
"Description = System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x800A03EC): Microsoft Office Excel cannot access the file 'E:\PC_MS\Data\Webfolders\CDNPLAN\AdminApp\Stage\Employee.xls'. There are several possible reasons:
u2022 The file name or path does not exist.
u2022 The file is being used by another program.
u2022 The workbook you are trying to save has the same name as a currently open workbook.
at Microsoft.VisualBasic.CompilerServices.LateBinding.LateGet(Object o, Type objType, String name, Object[] args, String[] paramnames, Boolean[] CopyBack)
at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack)
at ScriptTask_2921447fa19c44dfae73d5370828ba94.vbproj.ScriptMain.Main()
Now to crosscheck I commented the dynamic variables from the code and used same static values with Data manager as they are in BIDS but it didn't help, please find the code below and help me in solving this problem or just give me some clue to come out if this:
Thanks & Regards,
Rohit
Code
Public Sub Main()
' Add your code here
'Dim FileName As String = Dts.Variables("MYWEBFOLDERS").Value & Dts.Variables("MYAPPSET").Value & "\AdminApp\Stage\" & Dts.Variables("MYDIMNAME").Value & ".xls" This I commented as it was using dynamic variables
Dim FileName As String = "E:\PC_MS\Data\Webfolders\CDNPLAN\AdminApp\Stage\Employee.xls"
Dim WB As Object ' Workbook
Dim WS As Object 'Worksheet
Dim W As Object 'Window
Dim XL As Object 'Application
XL = CreateObject("Excel.Application")
XL.DisplayAlerts = False
' Open the workbook
WB = XL.Workbooks.Open(FileName)
' WB = GetObject(FileName)
' XL = WB.Parent
' XL.DisplayAlerts = False
WS = WB.Worksheets(1)
W = WB.Windows(WB.Name)
' Change the name of the worksheet to MEMBERS
WS.Name = "MEMBERS"
' Set up the split and freeze the panes
W.SplitRow = 1
W.SplitColumn = 1
W.Split = True
W.FreezePanes = True
' Make it visible
W.Visible = True
' Replace *ID column header with ID
Dim Row1 As Object
Row1 = WS.UsedRange.Rows("1:1")
Dim I As Integer
For I = 1 To Row1.Columns.Count
If Row1.Cells(I, 1).Value = "*ID" Then
Row1.Cells(I, 1).value = "ID"
Exit For
End If
Next
' Paste Values
WS.UsedRange.NumberFormat = "@"
WS.UsedRange.Value = WS.UsedRange.Value
' Change the font of everything to Arial,9
With WS.Cells.Font
.Name = "Arial"
.Size = 9
End With
' Format the top row to be bold and orange
With WS.Rows("1:1")
.Font.Bold = True
.Interior.ColorIndex = 44 'orange
End With
' Auto-fit all the columns
WS.Cells.EntireColumn.AutoFit()
' Convert to Excel format
Const xlNormal = -4143
WB.Parent.DisplayAlerts = False
WB.SaveAs(FileName:=FileName, FileFormat:=xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, CreateBackup:=False)
' Close and save changes
WS = Nothing
WB.Close()
W = Nothing
' Quit Excel
XL.Quit()
XL = Nothing
Dts.TaskResult = ScriptResults.Success
End SubHi,
If you do not define GLOBAL VARIABLE in your BPC package and BIDS, why don't you try to have it? you should specify the webfolder and file name in advanced script, then you also need to create global variable as text type in BIDS.
I saw many cases BPC does not pass the dynamic variable to BIDS, therefore I changed the type of variable as the Global variable and it works for me.
Regards,
YH Seo -
Convert ActiveX DTS script task to SSIS Script task - Please help
Hello,
I Have a ActiveX script that was used in a DTS package but I'm currently trying to convert all my DTS packages to SSIS.The script is tasked to run the package on a daily basis. Everything works fine except the ActiveX script. It gives an error on my DTSGlobalVariables.parent,
I looked up this error and changed it to "DTS.Variables("User::VariableName").Value", in
the SSIS script task (in VB) but now I'm getting error:
Microsoft.SqlServer.Dts.Runtime.DtsRuntimeException: The element cannot be found in a collection.
---> System.Runtime.InteropServices.COMException (0xC0010009): The element cannot be found in a collection.
bij Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSVariables100.get_Item(Object Index)
bij Microsoft.SqlServer.Dts.Runtime.Variables.get_Item(Object index)
--- Einde van intern uitzonderingsstackpad ---
bij Microsoft.SqlServer.Dts.Runtime.Variables.get_Item(Object index)
bij ST_f32fc12b60f34bebbbdfc0c5e5b40a96.vbproj.ScriptMain.Main()
--- Einde van intern uitzonderingsstackpad ---
bij System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
bij System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
bij System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
bij System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
bij System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
bij System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture)
I have tried to convert this ActiveX script into a SSIS script task in VB but I know hardly any VB... So I'm wondering what the best course of action for me is, should I try to convert it into the script task like I am trying now, if so, how do I make it
work?
Any help would be really really welcome.
This is the original ActiveX script that needs to be converted:
' Visual Basic ActiveX Script
Function Main()
Dim sEnvironm
Dim sServer
Dim sSourceFile
Dim sSourcePath
Dim sBackupPath
Dim sErrorPath
Dim sFileName
Dim sUDLPath
' Set vars
' First 2 are depending on the server and db
' FILL IN THE RIGHT VALUES
sEnvironm = "MON_Datamart"
sServer = "BrechtProesmans"
' --- DO NOT CHANGE ANYTHING BELOW THIS LINE ---
sSourceFile = "C:\Program Files\Microsoft SQL Server\MON_Datamart\SourceFiles\tbl_L00T1.txt"
sSourcePath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\SourceFiles\"
sBackupPath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\BackupFiles\"
sErrorPath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\ErrorFiles\"
sFileName = "tbl_L00T1.txt"
sUDLPath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\MON_Datamart.udl"
' Initial
FoundError = False
' Get a handle to the Package object.
Set oPackage = DTSGlobalVariables.Parent
' Update DTSConnections
Set oConnection = oPackage.Connections("tbl_L00T1.txt")
oConnection.DataSource = sSourceFile
Set oConnection = oPackage.Connections("Datamart")
oConnection.UDLPath = sUDLPath
Set oConnection = oPackage.Connections("Truncate")
oConnection.UDLPath = sUDLPath
' Update DTSTasks
Set oTask = oPackage.Tasks("DTSTask_DTSDataPumpTask_1").CustomTask
oTask.SourceObjectName = sSourceFile
oTask.DestinationObjectName = sEnvironm & ".dbo.stg_tbl_L00T1"
' Set Global vars
DTSGlobalVariables("SourcePath").Value = sSourceFile
DTSGlobalVariables("BackupPath").Value = sBackupPath
DTSGlobalVariables("ErrorPath").Value = sErrorPath
DTSGlobalVariables("FileName").Value = sFileName
' Clean up.
Set oTask = Nothing
Set oConnection = Nothing
Set oPackage = Nothing
Main = DTSTaskExecResult_Success
End FunctionSet a breakpoint and tell us on what line it dies, at the same time, you can inspect the variable values in the Auto window (if there are) as it merely perhaps is an issue with values not being passed in.
Arthur
MyBlog
Twitter -
Getting error message when i am trying to update the excel file using script task in ssis package
Hi Guys,
I am getting error message when I am trying to update the excel. Please find the error messages as below
Error at Update File [Update File]: Failed to compiled scripts contained in the package. Open the package in SSIS Designer and resolve the compilation errors.
Error at Update File [Update File]: BC30002 - Type 'Microsoft.Office.Interop.Excel.Application' is not defined., ScriptMain.vb, 32, 32
Error at Update File [Update File]: BC30002 - Type 'Microsoft.Office.Interop.Excel.Workbook' is not defined., ScriptMain.vb, 33, 25
Error at Update File [Update File]: The binary code for the script is not found. Please open the script in the designer by clicking Edit Script button and make sure it builds successfully.
Warning at Update File [Update File]: Found SQL Server Integration Services 2008 Script Task "ST_050fcae972904039b4f0fe59b7528ece" that requires migration!
and the code that I am using is
Dell - Internal Use - Confidential
' Microsoft SQL Server Integration Services Script Task
' Write scripts using Microsoft Visual Basic
' The ScriptMain class is the entry point of the Script Task.
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports Microsoft.Office.Interop.Excel
<System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="",
Description:="")> _
<System.CLSCompliantAttribute(False)> _
Partial
Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End Enum
Public Sub Main()
Dts.TaskResult = ScriptResults.Success
'Dim proc As System.Diagnostics.Process
'kill all instances of excel
'For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")
' proc.Kill()
'Next
Dim excelnacomm As
New Microsoft.Office.Interop.Excel.Application
Dim wbnacomm As Microsoft.Office.Interop.Excel.Workbook
wbnacomm = excelnacomm.Workbooks.Open("http://test.xlsx")(renamed
the excel)
wbnacomm.RefreshAll()
wbnacomm.Save()
wbnacomm.Close()
excelnacomm.Quit()
Runtime.InteropServices.Marshal.ReleaseComObject(excelnacomm)
End Sub
End
Class
Please let me know what could be the reason
Smash126Download:
Microsoft Office 2010: Primary Interop Assemblies Redistributable
How to: Add or Remove References By Using the Add Reference Dialog Box / How to:
Add and Remove References in Visual Studio (C#)
Olaf Helper
[ Blog] [ Xing] [ MVP] -
Hi Experts,
I am trying to open .xlsx file in script task of SSIS 2005. I am using the 32-bit AccessDatabaseEngine driver with the Connection string as "Provider= Microsoft.ACE.OLEDB.12.0; Data Source=xlsx file path; Extended Properties="Excel 12.0 Xml;
HDR=YES"" in script task.
When we debug the VB script in Visual Studio 2005 and encounters the statement app.open() it throws the error "Couldn't find installable ISAM".
My SQL server version is 2005 SP2 DE
OS is Windows server 2003 EE SP2
Could anyone please let me know what is the resolution for this error?
Thanks and Regards,
AdeshHi Adesh,
First, make sure the package runs in 32-bit runtime mode (set Run64BitRuntime property to False) because you are using the 32-bit ACE OLE DB Provider. If it is not the case, the issue may occur due to the corrupted drivers or registry keys. You can try to
reinstall the 2007 Office System Driver: Data Connectivity Components as Arthur suggested.
Regards,
Mike Yin
TechNet Community Support -
How to convert script output to excel and send through mail in the report
I need a solution for Converting script into EXCEL and sending Excel as a attachment to the mail. In my current Program I am getting OTF data from script and converting into PDF using Function module ' CONVERT_OTF'
And sending PDF as a mail attachment using Function module 'SO_NEW_DOCUMENT_SEND_API1' it is working fine but
My current requirement is I need to send Excel as a mail attachment instead of PDF.
Hope it is clear for you, please give me possible solutions with sample code..hi
good
CONSTANTS: CON_CRET TYPE X VALUE '0D', "OK for non Unicode
CON_TAB TYPE X VALUE '09'. "OK for non Unicode
*If you have Unicode check active in program attributes thnen you will
*need to declare constants as follows
*class cl_abap_char_utilities definition load.
*constants:
con_tab type c value cl_abap_char_utilities=>HORIZONTAL_TAB,
con_cret type c value cl_abap_char_utilities=>CR_LF.
CONCATENATE 'EBELN' 'EBELP' 'AEDAT' 'MATNR'
INTO IT_ATTACH SEPARATED BY CON_TAB.
CONCATENATE CON_CRET IT_ATTACH INTO IT_ATTACH.
APPEND IT_ATTACH.
LOOP AT IT_EKPO INTO WA_CHAREKPO.
CONCATENATE WA_CHAREKPO-EBELN WA_CHAREKPO-EBELP
WA_CHAREKPO-AEDAT WA_CHAREKPO-MATNR
INTO IT_ATTACH SEPARATED BY CON_TAB. " Check here
CONCATENATE CON_CRET IT_ATTACH INTO IT_ATTACH. " Check here
APPEND IT_ATTACH.
ENDLOOP.
thanks
mrutyun^ -
Creating Excel using C# in SSIS Script task.
Hi Guys,
I need to dynamically create an excel (with rows and columns) from a script task in a foreach container and just send an email to a group..
Can anyone guide me on this..
Thanks in advance...Hi,
There are a number of things wrong with this request.
1. This is a scripting forum, not a C# development forum.
2. This is not an SSIS forum.
3. You show nothing about what you have already tried, what has worked, and what hasn't worked.
Your question is far too broad and vague, and you're not even asking in the right place.
You need to break down your requirements into small pieces and ask very specific questions in the correct forums. If you need for someone to design a solution for you, it's better to hire a paid consultant.
Bill -
Unable to add reference for Excel Object Library for use within Script Task
I have a requirement to use a Script Tax that needs to reference the Excel Object Model. There are numerous articles on using this such as
http://www.databasejournal.com/features/mssql/article.php/3921141/SSIS-Script-Task-and-Microsoft-Office-Automation.htm.
Simply, I need to add a reference to the Microsoft Excel 12.0 Object Library.
I have selected this from the Object List on the COM tab and when this adds the reference it states 'The System cannot find the reference specified', even though the referenced file for this Object is C:\Program Files(x86)\Microsoft Office\Office12\Excel.exe
and this file location exists on my local machine ?Please search where "Microsoft.Office.Interop.Excel.dll" exist in your system and try adding the reference.
If you don't find the dll there then there might be problem while installing.
To install the PIAs by using the redistributable package
http://www.microsoft.com/en-us/download/details.aspx?id=3508
http://www.microsoft.com/en-us/download/details.aspx?id=18346
Regards, RSingh -
Using Script Task to rename an excel sheet.
I'm trying to use an SSIS Script Task to rename an excel sheet.
I've found several code samples on the net but most don't compile correctly and my knowledge of VB.net or C# isin't strong enough to fix the issues. I suspect they work but not for SSIS 2012 possibly.
Found the sample below which shows no errors at design time, but fails with an Invocation error so I'm unable to even trap what the error is to help in resolving the issue.
Does anyone have any sample code that they KNOW WORKS in SSIS 2012 or can see what the problem is ?
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:\Test.xlsx"
Try
xlBook = DirectCast(xl.Workbooks.Open(laPath, oMissing, oMissing, oMissing, oMissing, oMissing, _
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, _
oMissing, oMissing, oMissing), Workbook)
xlSheet = DirectCast(xlBook.Worksheets.Item(1), Worksheet)
xlSheet.Name = "Sheet1"
xlBook.Save()
xl.Application.Workbooks.Close()
Dts.TaskResult = ScriptResults.Success
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK)
Dts.Events.FireError(1, ex.TargetSite.ToString(), ex.Message.ToString(), "", 0)
Dts.TaskResult = ScriptResults.Failure
End Try
Thanks.Why do you need a script task for this? You can define the sheetname at the time of data transfer itself by creating a new sheet with required name
See this as an example
http://visakhm.blogspot.in/2013/09/exporting-sqlserver-data-to-multiple.html
Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page -
Script task to convert output from a sql query into send mail task body formatting
SSIS 2008R2 Version
Code from script task
Microsoft SQL Server Integration Services Script Task
Write scripts using Microsoft Visual C# 2008.
The ScriptMain is the entry point class of the script.
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
namespace ST_29dd6843bd6c4aee9b1656c1bbf55ba8.csproj
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
#region VSTA generated code
enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
#endregion
public void Main()
Variables varCollection = null;
string header = string.Empty;
string message = string.Empty;
Dts.VariableDispenser.LockForWrite("User::gsEmailMessage");
Dts.VariableDispenser.LockForWrite("User::gsWebserviceName");
Dts.VariableDispenser.LockForWrite("User::gsNoOfCallsInADay");
Dts.VariableDispenser.LockForWrite("User::gsCalledBySystem");
Dts.VariableDispenser.GetVariables(ref varCollection);
//Set the header message for the query result
if (varCollection["User::gsEmailMessage"].Value == string.Empty)
header = "Hi, Count is greater then 50 :\n\n";
//header = "Execute SQL task output sent using Send Email Task in SSIS:\n\n\n";
header += "----------------------------------------------------------------------------------------------------------------------" + "\n";
header += string.Format("{0}\t\t\t\t{1}\t\t{2}\n", "WebService Name", "No Of Calls In A Day", "Called By System");
header += "----------------------------------------------------------------------------------------------------------------------" + "\n";
varCollection["User::gsEmailMessage"].Value = header;
//Format the query result with tab delimiters
message = String.Format("<HTML><BODY><P>{0}</P><P>{1}</P><P>{2}</P></BODY></HTML>",
varCollection["User::gsWebserviceName"].Value,
varCollection["User::gsNoOfCallsInADay"].Value,
varCollection["User::gsCalledBySystem"].Value);
varCollection["User::gsEmailMessage"].Value = varCollection["User::gsEmailMessage"].Value + message + "\n";
Dts.TaskResult = (int)ScriptResults.Success;
Above code will return data in below format and then i send this output in aemail using send mail task.
Hi, count is greater then 50 :
WebService Name
No Of Calls In A Day Called By System
WebServiceone 1
Internetbutiken
WebServiceGetdetailstwo 1
Internetbutiken
Servicenamethree 2
MOB
As you can see above code is not in align as if we service name is shorter then 2nd column get disallign and its not look good.I need output should be like below.
Hi, count is greater then 50 :
WebService Name
No Of Calls In A Day Called By System
WebServiceone 1
Internetbutiken
WebServiceGetdetailstwo 1
Internetbutiken
Servicenamethree 2
MOB
Please suggest something...
Thanks
SR_MCTSSee code explained here
http://microsoft-ssis.blogspot.in/2013/08/sending-mail-within-ssis-part-2-script.html
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs
This will not help.As I am not creating smtp connectin ,send from ,send to in script task.I am just creating email body from sql output. -
Error While executing a SSIS package which contains a script task through SQL Server Agent job
Hi,
I have a SQL Server 2012 SSIS package with a script task along with other tasks [data flow, execute sql tasks ]. When I manually executed the job through BIDS, its completed successfully.
Then I have automated the execution of the package through SQL Server Agent Job. But when I executed the package through SQL Agent job, it runs successfully for all the tasks except script task. When it comes to execute the Script Task, it is getting failed
with the below error message.
"Error: 2012-08-29 12:45:14.67
Code: 0x00000001
Source: Script Task
Description: Exception has been thrown by the target of an invocation.
End Error
DTExec: The package execution returned DTSER_FAILURE (1).
Started: 12:45:10 PM
Finished: 12:45:14 PM
Elapsed: 4.353 seconds
I have installed the SSIS on the 64-bit environment and SSIS service is running. Also I tried to run the job through 32 bit [job option] but I am getting the above error in all cases.
Any help will be greatly appreaciated !
Thanks,
Navin
- naveen.reddyHi Arthur,
My script task access the excel files in a network share, refresh them all and save them. When I execute the ETL manually or thru DTEXEC, it is executing successfully. I am facing the issue when I am executing thru SQL Agent Job only. Logging also showing
the same error.
"Error: 2012-08-23 12:45:14.67
Code: 0x00000001
Source: Script Task
Description: Exception has been thrown by the target of an invocation.
End Error
DTExec: The package execution returned DTSER_FAILURE (1).
Started: 12:45:10 PM
Finished: 12:45:14 PM
Elapsed: 4.353 seconds
- naveen.reddy -
SSIS/Script Task/ VB 2008 Help Urgent...
Hi Guys,
Simple Script Task, just rename Excel tab, here is my code...
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports Microsoft.Office.Interop.Excel
Imports System.IO
Imports System.Text
<System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
<System.CLSCompliantAttribute(False)> _
Partial Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End Enum
Public Sub Main()
Dts.VariableDispenser.LockForRead("User::FileName") ' File Name Variable
Dim variablesList As Variables
Dts.VariableDispenser.GetVariables(variablesList)
'Dim SFileName As String
'SFileName = variablesList("User::Filename").Value.ToString
' Dim vars As Variables 'New Added For Variable
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
'Dts.VariableDispenser.LockForRead("Filename") 'New Added For Variable
'Start For Variable
'Dim File As String 'New Added For Variable
'File = CType(vars("Filename").Value, String) 'New Added For Variable
'MsgBox(Prompt:="Filename")
'Dim laPath As String = "C:\Excel\ABC_dr_daily_lf_10-07-14.xls" 'My File Name
Dim lapath As String = variablesList("User::FileName").Value.ToString 'New Added For Variable
'MsgBox(Prompt:="Filename")
xlBook = DirectCast(xl.Workbooks.Open(laPath, oMissing, oMissing, oMissing, oMissing, oMissing, _
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, _
oMissing, oMissing, oMissing), Workbook)
xlSheet = DirectCast(xlBook.Worksheets.Item(1), Worksheet)
xlSheet.Name = "data"
xlBook.Save()
xl.Application.Workbooks.Close()
Dts.TaskResult = ScriptResults.Success
End Sub
End Class
Finally I intalled MS Excel 2007 on my Dev Server. Here is the error that I am receiving....
Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidCastException:
Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel._Application
'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}'
failed due to the following error: Library not registered.
Please help me, this is very urgent.
Thank You.No I didn't upgrade my SQL Server. OMG this error making me ehhhhhh.
Here I solve my problem.
RUN>REGEDIT> and look for "Office.Interop.Excel" and delete the old version. I am using Excel 2007, 14.0.
It solve my Problem.
Thanks All. -
Error While executing script task componnent
Hi,
I am using script task comp in my package .script written in script task comp
' Microsoft SQL Server Integration Services Script Task
' Write scripts using Microsoft Visual Basic
' The ScriptMain class is the entry point of the Script Task.
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.IO
Imports System.Collections
Public Class clsCompareFileInfo
Implements IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
Dim File1 As FileInfo
Dim File2 As FileInfo
File1 = DirectCast(x, FileInfo)
File2 = DirectCast(y, FileInfo)
Compare = DateTime.Compare(File1.LastWriteTime, File2.LastWriteTime)
End Function
End Class
<System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
<System.CLSCompliantAttribute(False)> _
Partial Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End Enum
Public Sub Main()
Dim dirinfo As DirectoryInfo
Dim allFiles() As FileInfo
dirinfo = New DirectoryInfo(Dts.Variables("gsLaddningsKatalogSokvag").Value.ToString)
allFiles = dirinfo.GetFiles("*.txt")
'Sortera filerna efter "senast ändrad" så den fil med äldst "ändrad datum" kommer att laddas först
Array.Sort(allFiles, New clsCompareFileInfo)
For Each fl As FileInfo In allFiles
Dts.Variables("gsInFilNamnMedSokvag").Value = fl.FullName.ToString()
Dts.Variables("gsInFilNamn").Value = Path.GetFileName(fl.FullName.ToString())
Exit For
Next
Dts.TaskResult = ScriptResults.Success
End Sub
End Class
Error which i ma getting while running..
Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: The path is not of a legal form.
at System.IO.Path.NormalizePathFast(String path, Boolean fullCheck)
at System.IO.Path.NormalizePath(String path, Boolean fullCheck)
at System.IO.Path.GetFullPathInternal(String path)
at System.IO.DirectoryInfo..ctor(String path)
at ST_338efd96a3e940b0b489d5b5000f3397.vbproj.ScriptMain.Main()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture)
at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()
Please help.I am using sql server 2008R2 and visual studio 2008 BIDS.Hi,
I am using script task comp in my package .script written in script task comp
' Microsoft SQL Server Integration Services Script Task
' Write scripts using Microsoft Visual Basic
' The ScriptMain class is the entry point of the Script Task.
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.IO
Imports System.Collections
Public Class clsCompareFileInfo
Implements IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
Dim File1 As FileInfo
Dim File2 As FileInfo
File1 = DirectCast(x, FileInfo)
File2 = DirectCast(y, FileInfo)
Compare = DateTime.Compare(File1.LastWriteTime, File2.LastWriteTime)
End Function
End Class
<System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
<System.CLSCompliantAttribute(False)> _
Partial Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End Enum
Public Sub Main()
Dim dirinfo As DirectoryInfo
Dim allFiles() As FileInfo
dirinfo = New DirectoryInfo(Dts.Variables("gsLaddningsKatalogSokvag").Value.ToString)
allFiles = dirinfo.GetFiles("*.txt")
'Sortera filerna efter "senast ändrad" så den fil med äldst "ändrad datum" kommer att laddas först
Array.Sort(allFiles, New clsCompareFileInfo)
For Each fl As FileInfo In allFiles
Dts.Variables("gsInFilNamnMedSokvag").Value = fl.FullName.ToString()
Dts.Variables("gsInFilNamn").Value = Path.GetFileName(fl.FullName.ToString())
Exit For
Next
Dts.TaskResult = ScriptResults.Success
End Sub
End Class
Error which i ma getting while running..
Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --->
System.ArgumentException: The path is not of a legal form.
Hi SR_MCTS,
The error message how the path is not of a legal form, please take a look at the highlight content in above message. Please try to use the following code:
dirinfo = new DirectoryInfo(Dts.Variables["User::Local_Dir"].Value.ToString)
Please ensure you have configure the vaild path for "Local_Dir" variable. For more information, you can take a look at the following thread:
http://social.msdn.microsoft.com/forums/sqlserver/en-US/f073ecef-37ed-4a4c-bee6-d9ef66ff471d/filesystem-task-issue-ssis
Regards,
Elvis Long
TechNet Community Support -
SSIS Script task not executing macro through SQL Agent (but it does through bids)
<p>Hello everyone,</p><p>I am having an issue with SQL Agent when executing a macro contained in a script task component. The script task actually opens an excel file, runs the macro, save and closes the file. </p><p>When
I execute the package via BIDS/Visual studio, it works like a charm. However, when i execute the package with SQL agent, the package runs successfully but it seems that the macro is not executed as the excel file has not been modified as it should have. Also,
the history log does not show any error messages. </p><p>Could </p>Thanks!I did create a credential and a proxy too but still the macro is not executed.I have searched online for solutions but no one has experimented this kind of issue before it seems. Please have a look at the script task code:
Imports
Excel = Microsoft.Office.Interop.Excel
Imports
System
Imports
System.Data
Imports
System.Math
Imports
Microsoft.SqlServer.Dts.Runtime
<System.AddIn.AddIn(
"ScriptMain", Version:="1.0",
Publisher:="", Description:="")>
<System.CLSCompliantAttribute(
False)> _
Partial
Public
Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End
Enum
Public
Sub Main()
Dim Macro_name
As
String
Dim ExcelObject
As
New Microsoft.Office.Interop.Excel.Application
Dim oBook
As Microsoft.Office.Interop.Excel.Workbook
Dim oBooks
As Microsoft.Office.Interop.Excel.Workbooks
Try
Macro_name =
"Macro001"
ExcelObject =
CType(CreateObject("Excel.Application"),
Excel.Application)
ExcelObject.Visible =
True
ExcelObject.UserControl =
False
ExcelObject.DisplayAlerts =
False
oBooks = ExcelObject.Workbooks
oBook =
CType(oBooks.Open("C\Book1.xls"),
Excel.WorkbookClass)
ExcelObject.Run(Macro_name)
Catch ex
As Exception
ExcelObject.Application.Quit()
ExcelObject.DisplayAlerts =
True
ExcelObject =
Nothing
End
Try
Dts.TaskResult = ScriptResults.Success
End
Sub
End
Class -
How can apply configure file in ssis by using script task ?
I had two config file in ssis
1. config file as per QA
2. config file as per Production
I think apply dynamically by using script task for above file (acc to server)
How can I apply in script task for config file path in C# script
any one provide Helpful code ??
ThanksI applied script Task with below code :
public void Main()
//User::Config,User::Config_Pd,User::Config_QA
Application App = new Application();
Package Pack = new Package();
DTSExecResult pkgResults;
string strPackageName;
string filename = "";
string configvalue;
configvalue = Dts.Variables["Config"].Value.ToString();
strPackageName = Directory.GetCurrentDirectory().ToString() + "\\Excel Reports from Remittance advice\\Child.dtsx";
try
Pack = App.LoadPackage(strPackageName, null);
if (Pack != null)
if (configvalue == "DEV")
filename = Dts.Variables["Config_QA"].Value.ToString();
else if (configvalue == "PROD")
filename = Dts.Variables["Config_Pd"].Value.ToString();
else
Dts.TaskResult = (int)ScriptResults.Failure;
System.Windows.Forms.MessageBox.Show("Unable to bind the XML Configurations");
return;
} System.Windows.Forms.MessageBox.Show("Config:"+filename);
Pack.ImportConfigurationFile(@filename);
Pack.EnableConfigurations = true;
Pack.Configurations.Add();
App.SaveToXml(strPackageName, Pack, null)
pkgResults = Pack.Execute(); //Pack.Execute();
System.Windows.Forms.MessageBox.Show("Results:" + pkgResults.ToString());
Dts.TaskResult = (int)ScriptResults.Success;
But ouput in ssis showing as
But some thing missed in code plz help me ...
Maybe you are looking for
-
Return the file name of the field type BLOB
How can I create the PL/SQL procedure that return the file name of the file insert into the record with a field file_date BLOB. I have this table: TEST with this item: file_name varchar2(20) file_date blob example I have insert with the OraclePortal
-
CRM PCUI Issue; tab product; no of items displayed configurable?
Hello everybody, I am facing one CRM PCUI problem. customer would like to set no of items, which can be max. displayed in CRM PCUI application CRMD_BUS2000115, on tab "product" on Level "Detail Area 1". As default max. 10 could be displayed, this is
-
Audio lost from Keynote 09 import to iPad
I thought the recent Keynote for iPad software update was supposed to allow importing audio from Keynote 09 files. I still have no audio with these files on the iPad. Suggestions?
-
Hi Gurus, In SAP PLM integrated to ProE, I have opened an assembly in proe and through CAD VIEW from SAP PLM, I have created DIR for the assembly and its dependent components. If I try to check in the assembly (Originals-Check in Originals) in CAD VI
-
Changing Contact Settings asks for Old Facebook Details!!!
So!! when I change my contact settings on my i-pad it asks for my old Facebook password for my old account, with my old e-mail. Then it displays "Settings" and "Cancel" as the only two options. When I click on "Settings" it takes me to the Facebook t