Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 6882
  • Last Modified:

SSIS - Help With Creating Dynamic Sheet Name (Excel Import)

Hi there, I am out of the loop on creating custom SSIS packages.  I have a package already created ... but I have been having issues with it and realized its because the people who send me the excel files are changing the name of the Sheets every time they run.  So, I'd like the package to just automatically get the name of the sheet.  It will always be the first sheet but just the name of it is changing.  

I found this link:
http://stackoverflow.com/questions/4444169/import-data-from-excel-using-ssis-without-knowing-sheet-name

Which has some script task to do what I want to do... but I'm a dummy and I have no idea what I need to do to my package to put the script task in and make it work properly.  

Can anybody walk me through it?  Thanks.
0
Roxanne25
Asked:
Roxanne25
  • 7
  • 4
4 Solutions
 
Sreedhar VengalaSr. Consultant - Business IntelligenceCommented:
What I would suggest is to have Script Task as a starting point to read the the Excel Workbook and rename the Sheet1 to a standard name.

Then the normal steps of reading sheet1 and doing your data loads.

You can have something like in your Script task for renaming the worksheet.

using Excel = Microsoft.Office.Interop.Excel; 

    object oMissing = System.Reflection.Missing.Value;
    Excel.ApplicationClass xl=new Excel.ApplicationClass();
        Excel.Workbook xlBook;
        Excel.Worksheet xlSheet;
        string laPath = Server.MapPath(@"\excel\xl_table.xls");
        xlBook = (Workbook)xl.Workbooks.Open(laPath,oMissing,
          oMissing,oMissing,oMissing ,oMissing,oMissing,oMissing
         ,oMissing,oMissing,oMissing,oMissing,oMissi ng,oMissing,oMissing);
        xlSheet = (Worksheet)xlBook.Worksheets.get_Item(1);
        xlSheet.Name = "CIAO";
        xlBook.Save();
        xl.Application.Workbooks.Close();

Open in new window

0
 
Roxanne25Author Commented:
Ooo nice, thank you I will try that tomorrow.  From the toolbox though, which object do I chose to add the script task?  Is it the one that says component script?  I didn't see one that actually just said script task.
0
 
Sreedhar VengalaSr. Consultant - Business IntelligenceCommented:
When you are in Control Flow Tab you can find 'Script Task' under Common Components of Toolbox.

Script Task
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
Roxanne25Author Commented:
Right, I hadn't looked at the question yet today but I did see it there and felt really dumb for asking that question... but thank you for pointing it out.  I will try your code now! :)
0
 
Roxanne25Author Commented:
Ok, I got the task in and tried to add the code ... I am getting a red "x" on the script task that says "the binary code for this script is not found."

This is the code that is in the editor:

/*
   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;
using Excel = Microsoft.Office.Interop.Excel; 

namespace ST_85e11ab01ac4476dbca6f7a12f259ae0.csproj
{
    [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
    public 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

        /*
		The execution engine calls this method when the task executes.
		To access the object model, use the Dts property. Connections, variables, events,
		and logging features are available as members of the Dts property as shown in the following examples.

		To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
		To post a log entry, call Dts.Log("This is my log text", 999, null);
		To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);

		To use the connections collection use something like the following:
		ConnectionManager cm = Dts.Connections.Add("OLEDB");
		cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";

		Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
		
		To open Help, press F1.
	*/

        public void Main()
        {
            // TODO: Add your code here
            
            
            object oMissing = System.Reflection.Missing.Value;
            Excel.ApplicationClass xl=new Excel.ApplicationClass();
                Excel.Workbook xlBook;
                Excel.Worksheet xlSheet;
                string laPath = Server.MapPath(@"\\calapps\msds\pom support\slamis app docs\SBDataLoad\appendixd.xls");
                xlBook = (Workbook)xl.Workbooks.Open(laPath,oMissing,
                  oMissing,oMissing,oMissing ,oMissing,oMissing,oMissing
                 ,oMissing,oMissing,oMissing,oMissing,oMissi ng,oMissing,oMissing);
                xlSheet = (Worksheet)xlBook.Worksheets.get_Item(1);
                xlSheet.Name = "Sheet1";
                xlBook.Save();
                xl.Application.Workbooks.Close(); 

            Dts.TaskResult = (int)ScriptResults.Success;
        }
    }
}

Open in new window


There are red underlines on some of the code that you gave me.  "Server." is underlined in red, Workbook is underlined in red as well as Worksheet.
0
 
Roxanne25Author Commented:
Hi, just checking to see if you had any further guidance on the post I made last week?  Thanks!
0
 
Sreedhar VengalaSr. Consultant - Business IntelligenceCommented:
Ok here is the working code:

using System.Runtime.InteropServices;
using Microsoft.SqlServer.Dts.Runtime;
using Microsoft.SqlServer.Dts.Tasks.ScriptTask;

namespace ST_305e53f071d14e419306294397c38156
{
    [SSISScriptTaskEntryPoint]
    public class ScriptMain : VSTARTScriptObjectModelBase
    {
        public void Main()
        {
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            excelApp.DisplayAlerts = false;

            string workbookPath = @"C:\SWs\test.xlsx";

            Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
                    0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
                    true, false, 0, true, false, false);

            Microsoft.Office.Interop.Excel.Worksheet wksheet = excelWorkbook.Worksheets[1];

            

            wksheet.Name = "Total Monthly";

            excelWorkbook.Save();

            excelWorkbook.Close();

            Marshal.ReleaseComObject(wksheet);

            excelApp.Quit();
            Dts.TaskResult = (int) ScriptResults.Success;
        }

Open in new window


Note:  Code is done on VS2012 / with Excel 2013 dlls.

Imp:  
1. Make sure you reference Microsoft.Office.Interop.Excel and Microsoft.Csharp dlls in your script task project code.
2. Replace the harded coded filename @"C:\SWs\test.xlsx" with appropriate variablename which holds the filename and is dynamic for each run.

Hope this help you out.
0
 
Roxanne25Author Commented:
Ok I added the reference for Excel... I can't find anything for adding CSharp.  So, not sure about that one.  

I put your new code in but it still will not build.  It is giving me the following errors now:

The type or namespace name 'SSISScriptTaskEntryPointAttribute' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'SSISScriptTaskEntryPoint' could not be found(are you missing a using directive or an assembly reference?)


I am using Visual Studio 2008 BTW if that makes any difference.
0
 
Roxanne25Author Commented:
Ok, so I gave up with C# ... VB is easier... lol.

I did this:

' Microsoft SQL Server Integration Services Script Task
' Write scripts using Microsoft Visual Basic 2008.
' The ScriptMain is the entry point class of the script.

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
	

	' The execution engine calls this method when the task executes.
	' To access the object model, use the Dts property. Connections, variables, events,
	' and logging features are available as members of the Dts property as shown in the following examples.
	'
	' To reference a variable, call Dts.Variables("MyCaseSensitiveVariableName").Value
	' To post a log entry, call Dts.Log("This is my log text", 999, Nothing)
	' To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, True)
	'
	' To use the connections collection use something like the following:
	' ConnectionManager cm = Dts.Connections.Add("OLEDB")
	' cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;"
	'
	' Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
	' 
	' To open Help, press F1.

	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 = "\\calapps\msds\pom support\slamis app docs\SBDataLoad\appendixd.xls"
        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
    End Sub

End Class

Open in new window


And it builds and it works woo hoo!

However, now I'm running into the problem with running the entire package... my data flow task won't validate because the sheet name isn't what it is looking for cause it hasn't ran the script task yet.  

Is there a way to force it to not validate until after it does the script task?  Or is the solution here to put the sheet name into a variable and plug that into the data source instead?
0
 
Sreedhar VengalaSr. Consultant - Business IntelligenceCommented:
You should set Delay validation property on you Data Flow task to true.
0
 
Roxanne25Author Commented:
Sweet thank you!  I was hoping there was something like that!  Thank you so much for your assistance.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 7
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now