Solved

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

Posted on 2014-03-13
11
5,810 Views
Last Modified: 2016-02-10
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
Comment
Question by:Roxanne25
  • 7
  • 4
11 Comments
 
LVL 9

Assisted Solution

by:Sreedhar Vengala
Sreedhar Vengala earned 500 total points
ID: 39928085
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
 

Author Comment

by:Roxanne25
ID: 39928232
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
 
LVL 9

Assisted Solution

by:Sreedhar Vengala
Sreedhar Vengala earned 500 total points
ID: 39928288
When you are in Control Flow Tab you can find 'Script Task' under Common Components of Toolbox.

Script Task
0
 

Author Comment

by:Roxanne25
ID: 39929172
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
 

Author Comment

by:Roxanne25
ID: 39929233
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:Roxanne25
ID: 39936963
Hi, just checking to see if you had any further guidance on the post I made last week?  Thanks!
0
 
LVL 9

Accepted Solution

by:
Sreedhar Vengala earned 500 total points
ID: 39938769
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
 

Author Comment

by:Roxanne25
ID: 39945263
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
 

Author Comment

by:Roxanne25
ID: 39946064
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
 
LVL 9

Assisted Solution

by:Sreedhar Vengala
Sreedhar Vengala earned 500 total points
ID: 39946546
You should set Delay validation property on you Data Flow task to true.
0
 

Author Comment

by:Roxanne25
ID: 39946564
Sweet thank you!  I was hoping there was something like that!  Thank you so much for your assistance.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Lessons learned during ten years of interviewing for SQL Server Integration Services (SSIS) and other Extract-Transform-Load (ETL) contract roles and two years of staff manager interviewing contractors.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now