Click here to Skip to main content
15,922,533 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have below c sharp code in script component(transformation) in ssis package which will load data from single sheet from each workbook. Now requirement changed and have more than 15 excel workbooks which have multiple sheets and I need to automate bringing that data into SQL server table.

Is there a way to pull data from Excel only from particular sheets? It seems to rely on the sheet name as the data source, for example ExcelworkbookA have 7 shets but need data only from three sheets.
Anyone suggest me how to modify below code to allow multiple sheets from exceworkbooks


#region Help: Introduction to the Script Component
/* The Script Component allows you to perform virtually any operation that can be accomplished in
* a .Net application within the context of an Integration Services data flow.
*
* Expand the other regions which have "Help" prefixes for examples of specific ways to use
* Integration Services features within this script component. */
#endregion

#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.Data.OleDb;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
#endregion

/// <summary>
/// This is the class to which to add your code. Do not change the name, attributes, or parent
/// of this class.
///
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
#region Help: Using Integration Services variables and parameters
/* 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 component, according to whether or not your
* code needs to write into the variable. To do so, 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 or parameter:
* DateTime startTime = Variables.MyStartTime;
*
* Example of writing to a variable:
* Variables.myStringVariable = "new value";
*/
#endregion

#region Help: Using Integration Services Connnection Managers
/* Some types of connection managers can be used in this script component. See the help topic
* "Working with Connection Managers Programatically" for details.
*
* To use a connection manager in this script, first ensure that the connection manager has
* been added to either the list of connection managers on the Connection Managers page of the
* script component editor. To add the connection manager, save this script, close this instance of
* Visual Studio, and add the Connection Manager to the list.
*
* If the component needs to hold a connection open while processing rows, override the
* AcquireConnections and ReleaseConnections methods.
*
* Example of using an ADO.Net connection manager to acquire a SqlConnection:
* object rawConnection = Connections.SalesDB.AcquireConnection(transaction);
* SqlConnection salesDBConn = (SqlConnection)rawConnection;
*
* Example of using a File connection manager to acquire a file path:
* object rawConnection = Connections.Prices_zip.AcquireConnection(transaction);
* string filePath = (string)rawConnection;
*
* Example of releasing a connection manager:
* Connections.SalesDB.ReleaseConnection(rawConnection);
*/
#endregion

#region Help: Firing Integration Services Events
/* This script component can fire events.
*
* Example of firing an error event:
* ComponentMetaData.FireError(10, "Process Values", "Bad value", "", 0, out cancel);
*
* Example of firing an information event:
* ComponentMetaData.FireInformation(10, "Process Values", "Processing has started", "", 0, fireAgain);
*
* Example of firing a warning event:
* ComponentMetaData.FireWarning(10, "Process Values", "No rows were received", "", 0);
*/
#endregion

/// <summary>
/// This method is called once, before rows begin to be processed in the data flow.
///
/// You can remove this method if you don't need to do anything here.
///
public override void PreExecute()
{
base.PreExecute();
/*
* Add your code here
*/
}

/// <summary>
/// This method is called after all the rows have passed through this component.
///
/// You can delete this method if you don't need to do anything here.
///
public override void PostExecute()
{
base.PostExecute();
/*
* Add your code here
*/
}

public override void CreateNewOutputRows()
{
/*
Add rows by calling the AddRow method on the member variable named "Buffer".
For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".
*/

try
{

string filename = Variables.SharepointFilepath.ToString();
//string sheetName; //= Variables.ExcelSheetName.ToString();

Excel.Application xlApp = new Excel.Application();
xlApp.Visible = false;
xlApp.DisplayAlerts = false;
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filename, Password: "'");
Excel.Worksheet xlWorkSheet = xlWorkBook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;

Excel.Range UsedRange = xlWorkSheet.UsedRange;


foreach (Excel.Range c in UsedRange)
{
string val = Convert.ToString(c.Value2);
if (val != "" && val != null)
{
Output0Buffer.AddRow();
Output0Buffer.Row = c.Row;
Output0Buffer.Column = c.Column;
Output0Buffer.Value = val;
}
}



xlApp.Quit();
xlApp = null;

GC.Collect();
GC.WaitForPendingFinalizers();

}

catch (Exception e)
{
Output1Buffer.AddRow();
Output1Buffer.Exception = e.ToString();
}

}

}

What I have tried:

Tried with variable but no luck
Posted
Updated 9-Apr-18 2:28am
Comments
#realJSOP 9-Apr-18 8:12am    
Are the filenames and sheet names always the same?
Member 13769780 9-Apr-18 8:32am    
yes filenames and sheet names always same

1 solution

0) First, I wouldn't use a script task to import an excel file unless I absolutely had to. There is built-in importer functionality that makes it far easier to do.

1) I would create a separate importer package for each worksheet. Why? Because SSIS error reporting sucks wild donkey schlongs, and a failure anyplace in the importing process could crash the entire package, and thus cause the associated SQL agent to fail. It's MUCH easier to zero-in on failures when you have an agent that runs a "step" for each package. The only possible downside to this is that the filenames and worksheet names must always be the same name, and the sheets must always have the same columns formatted the same way.

2) If you insist on using a script task (again, I suggest you don't do this), I posted an article over the weekend that allows you to load an excel file (WITHOUT USING EXCEL INTEROP) into a DataTable that can then be used to move the data into a database - CSV/Excel File Parser - A Revisit[^]
 
Share this answer
 
v2
Comments
Member 13769780 9-Apr-18 8:33am    
Thanks. In the article CSV/Excel File Parser - A Revisit[^] which part do I need to consider. Sorry I have very little experience in scripts. please suggest
#realJSOP 9-Apr-18 10:18am    
The code in that article will allow you to import an excel spreadsheet - all you need to do is provide the filename and sheet name. What you do with the data after it's been parsed is really up to you. a Script task is nothing more than a C# assembly that you compile. Anything you can do in c#, you can do in a script. IMHO, if you're not schooled up on this (SSIS, and C#), you're the wrong person to be modifying the script, because a small mistake on your part could destroy your existing data.

The article has code, and provides sample usage for both Excel and CSV files. You should review it and evaluate its suitability for your task before using it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900