3

The problem:

I have an SSIS package that loops through 100+ Excel files and reads the data, then copies the contents over to a SQL Server Table. In these Excel files, this one column has hyperlinks. The column text itself says something like DSH-LN-4, but clicking on it in Excel opens up a folder that contains some images. How do I copy the underlying link in this column rather than the actual text in the cells?

What have I tried so far:

I haven't really tried anything because I found absolutely no resources on how to do this in SSIS. Manually adding a column to the Excel files is NOT possible, since there are 100's of files. The only resource I found was in this SO Question, but this does not indicate the process of doing this without manually manipulating the Excel files.

What I would like:

In my ForEach loop container, I have a data flow task that gets the Excel contents and shoves it into the SQL Table. The column that contains hyperlinks is called PhotoReference (since these hyperlinks open the folder that has the photos). I would like this PhotoReference column to copy over the underlying hyperlink of the cell and add that to the SQL column.

For instance, I want the PhotoReference column to contain this:

www.companyname.box.com/asjdfbgkjb134kjbsdafo2bm21n4bk

If I can manage to do this, my Power BI report running off of this underlying data could contain a clickable text that would open the image directly.

Any help would be appreciated.

UPDATE:

I was able to try two different methods to extract the hyperlinks from my column, but each of these have their own issues:

Method 1: I added a Script Task component to my ForEach container and as I loop through each Excel file, used Microsoft.Office.Interop.Excel.Hyperlinks assembly to get the hyperlink from my Excel column. BUT, I don't know what to do with it after. I figured the only thing to do is to overwrite the Excel columns' content with my extracted hyperlink, but I really rather not change my Excel files in any manner.

Method 2: I added a Script Component object inside my data flow task in between my Excel source and SQL Destination. In this method, I could not get nearly as far because the Input0_ProcessInputRow method that is auto-generated has the argument Row of type Input0Buffer. I am not able to apply any Microsoft.Office.Interop.Excel properties to my Input0Buffer object. So I am stuck.

2
  • 1
    In the for each loop container you should add a Script Task to extract the content to another column before reading the Excel in the data flow task. I will try to provide a detailed answer in a while
    – Hadi
    Commented Jan 2, 2020 at 20:21
  • Thank you @Hadi, I'd appreciate a more detailed explanation on how to do that. I am struggling with using the Input0Buffer Row I get in Script Component method with the Interop.Excel assemblies to extract hyperlinks. Commented Jan 2, 2020 at 21:35

2 Answers 2

2
+50

If you have to right to alter the excel files, you can simply add a Script Task before the data flow task to replace the URL column value with the hyperlink.

In this answer, I will provide a step-by-step solution to solve this problem:

Creating Excel samples

First of all, I created some Excel files with the following columns:

  • First name (text)
  • Last name (text)
  • Age (number)
  • Photo (hyperlink)

The file content looks like the following:

enter image description here

Creating the SSIS package

  1. First of all, You must add an Excel connection manager that link to one of the Excel files you need to import. And an OLE DB connection manager to connect to the SQL Server instance.
  2. You must add a SSIS variable of type string, to store the Excel file path when using the foreach enumerator

enter image description here

  1. Add a Foreach loop container and configure it to loop over the Excel files as mentioned in the images below:

enter image description here

enter image description here

  1. Within the Foreach Loop container add a Script Task and a Data flow task as mentioned in the image below:

enter image description here

  1. Now, Open the data flow task and add an Excel source and an OLE DB destination and configure the columns mapping between them.

  2. Open the Script Task configuration, and select the ExcelFilePath variable (created in step 2) as a readonly variable as mentioned in the image below:

enter image description here

  1. Now, open the Script editor and in the solution explorer window, right-click on the references icon and click on "Add Reference..."
  2. When the Add reference catalog appears, click on the COM tab, and search for Excel, then you should select the Excel Object Library from the results as shown in the following image:

enter image description here

  1. Also, make sure to add Microsoft.CSharp.dll reference.
  2. On the top of the script you should add the following line:

    using Excel = Microsoft.Office.Interop.Excel;
    using System.Runtime.InteropServices;
    
  3. In the Main() function add the following lines:

    Excel.Application excel = new Excel.Application();
    string originalPath = Dts.Variables["User::ExcelFilePath"].Value.ToString();
    Excel.Workbook workbook = excel.Workbooks.Open(originalPath);
    Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];
    Excel.Range usedRange = worksheet.UsedRange;
    int intURLColidx = 0;
    
    excel.Visible = false;
    excel.DisplayAlerts = false;
    
    for (int i = 1; i <= usedRange.Columns.Count; i++)
    {
    
    
        if ((worksheet.Cells[1, i] as Excel.Range).Value != null &&
            (string)(worksheet.Cells[1, i] as Excel.Range).Value == "Photo")
        {
    
            intURLColidx = i;
            break;
    
        }
    
    
    
    }
    
    for (int i = 2; i <= usedRange.Rows.Count; i++)
    {
    
        if ((worksheet.Cells[i, intURLColidx] as Excel.Range).Hyperlinks.Count > 0)
        {
            (worksheet.Cells[i, intURLColidx] as Excel.Range).Value2 = (worksheet.Cells[i, intURLColidx] as Excel.Range).Hyperlinks.Item[1].Address.ToString();
        }
    }
    
    workbook.Save();
    
    Marshal.FinalReleaseComObject(worksheet);
    
    workbook.Close(Type.Missing, Type.Missing, Type.Missing);
    Marshal.FinalReleaseComObject(workbook);
    
    excel.Quit();
    Marshal.FinalReleaseComObject(excel);
    Dts.TaskResult = (int)ScriptResults.Success;
    

In the lines above, first we searched for the column index that contains the hyperlink (in this example the column name is "Photo", then we will check for each line if the Hyperlink address is not empty we will replace the column value with this hyperlink address)

  1. Finally, make sure to configure the Excel connection manager to read the file path from the created variable value (Step 2) using expressions:

enter image description here

Experiments

After running the package, if we open an Excel file we will see that the Cell value is replaced with the URL:

enter image description here

And as shown in the image below, data are imported successfully to SQL Server:

enter image description here


References

10
  • 1
    Thank you so much, I am doing this right now. I would have liked a way to do this without altering the Excel files, but I am making a local copy of cloud controlled Excel files anyway, so it should not really matter. I will try this out and get back to you. Commented Jan 2, 2020 at 22:38
  • @CrazyCucumber If you cannot alter Excel files, you should use a Script Component to loop over rows, alter the hyperlink column value, generate SSIS buffer rows and close Excel without saving. But this is a more complex approach. I think it is easier to take a copy of the files and use Script Task
    – Hadi
    Commented Jan 2, 2020 at 22:44
  • 1
    Yup! I figured after seeing your Excel file format. Thanks a lot, running it now. Commented Jan 2, 2020 at 22:52
  • 2
    DelayValidation was true already due to needing Expression for the ConnectionManager. The Excel process though, did the trick. There were FIFTEEN open! LOL. Gonna look at maybe ending processes in SSIS too, so the job does not complete and leave a sloppy mess behind. You, kind human, are WONDERFUL! Thank you so much! I will reward the bounty as soon as I can. P.S.: I made one change: Removed the entire section that referred to intURLColidx. I knew the URL exists and I knew it for a fact exists in column number 21. So I just hard-coded that. Commented Jan 2, 2020 at 23:35
  • 1
    @CrazyCucumber happy to hear that. The weird thing is that the last lines are to kill the process, it looks like there is something missing. And concerning the bounty, it will be automatically awarded after 7 days since you marked this answer as accepted.
    – Hadi
    Commented Jan 2, 2020 at 23:44
0

What you will probably need to do is some hackery involving the Excel COM API, or macros. In fact, since you should stay away from using the Office COM API in SSIS.

You could pre-process excel to take that value with non-standard operations in SSIS, like using script component.

These are the steps you need to follow to import that data using the Script component:

  1. Drag and drop a script component and select "source" as the script option type.

  2. By default the script language is Microsoft Visual C# 2008 and I have done this sample with Microsoft Visual Basic 2008. Change this if you need to.

  3. Define your output columns with the correct data type in "data type properties"

  4. Edit the script. In the IDE you should add reference:

    • Microsoft.Excel 11.0 Object Library

(if that reference doesn´t work, try with Microsoft.Excel 5.0 Object Library)

  1. Finally, write some code:

Imports Microsoft.Office.Interop.Excel 

Public Overrides Sub getHyperlink()
  Dim oExcel As Object = CreateObject("Excel.Application")
  Dim FileName As String
  FileName = Variables.FileName
  Dim oBook As Object = oExcel.Workbooks.Open(FileName)
  Dim oSheet As Object = oBook.Worksheets(1)
  Output0Buffer.AddRow()
  // change A1 with your correct col & row
  Output0Buffer.Address = cell.range("A1").Hyperlinks(1).Address & "#" & cell.range("A1").Hyperlinks(1).SubAddress

End Sub

(keep in mind that it is a code that may not run, it is by way of illustration)

You could see code in C# here: C# Script in SSIS Script Task to convert Excel Column in "Text" Format to "General"

The only issue with the script method is you need to have the Excel runtime installed.

More about script component here: https://www.tutorialgateway.org/ssis-script-component-as-transformation/

1
  • Thank you for your answer. I am working on the script component right now. The only issue I am having is, should I add the script component as a Transformation Script component in the Data Flow Task? Or should I add it outside the Data Flow task? I have figured a way to add it outside and traverse through the hyperlinks, but I am not sure on how to write the read hyperlinks somewhere. If I use it in the Data Flow task, I am not sure how to use the Excel com objects in Input0Buffer row object. Any guidance on that? Commented Jan 2, 2020 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.