Reputation: 35
Good evening everyone. I have to build a SSIS package that does as follows:
1) Execute a VBA code to a XLS file (Transpose a range into another range) 2) Save the XLS (In the same file or as a new file) 3) Import the modified XLS from the Transposed range.
Basically I have to transpose the data inside a XLS that I must import, and I didn't find a good way to do that in SSIS (Since the column range can change between files)
With this simple VBA script I can do that and make SSIS read the data in a very straightforward way. However I'm not finding a way to apply this code without modifying the Excel previously manually to add the script and run the VBA script. I want to automate this so the package prepares the xls, extracts the new data, and save it to a table.
Can anyone shed some ideas on how to apply this code or other ways to do this? The most important point I think is that it's a very specific range that I want to transpose.
Sub myTranspose()
With Range("a18:ZZ27", Range("a18:ZZ27").End(xlDown))
.Copy
Range("a30").PasteSpecial Transpose:=True
End With
End Sub
Upvotes: 1
Views: 3513
Reputation: 1861
Create a Script Task that is piped into a Data Flow task
Edit the Script Task by double clicking the Script Task and clicking the Edit Script button.
Add references to Excel and CSharp as seen in this answer
Add some code similar to the following:
public void Main()
{
string filepath = @"c:\temp\transpose.xlsx";
Excel.Application xlApp;
Excel._Workbook oWB;
try
{
xlApp = new Excel.Application();
xlApp.Visible = false;
oWB = (Excel.Workbook)xlApp.Workbooks.Open(filepath);
Excel.Range fromrng = xlApp.get_Range("B4", "F5");
Object[,] transposedRange = (Object[,])xlApp.WorksheetFunction.Transpose(fromrng);
Excel.Range to_rng = xlApp.get_Range("A8", "A8");
to_rng = to_rng.Resize[transposedRange.GetUpperBound(0), transposedRange.GetUpperBound(1)];
to_rng.Value = transposedRange;
xlApp.ActiveWorkbook.Save();
oWB.Close(filepath);
}
catch (Exception ex)
{
//do something
}
Dts.TaskResult = (int)ScriptResults.Success;
}
This gives the following result in the sample transpose.xlsx I created.
Upvotes: 2